I'm currently working on a project which needs to persist any kind of object (of which implementation we don't have any control) so these objects could be recovered afterwards.
We can't implement an ORM because we can't restrict the users of our library at development time.
Our first alternative was to serialize it with the Java default serialization but we had a lot of trouble recovering the objects when the users started to pass different versions of the same object (attributes changed types, names, ...).
We have tried with the XMLEncoder class (transforms an object into a XML), but we have found that there is a lack of functionality (doesn't support Enums for example).
Finally, we also tried JAXB but this impose our users to annotate their classes.
Any good alternative?
It's 2011, and in a commercial grade REST web services project we use the following serializers to offer clients a variety of media types:
XStream (for XML but not for JSON)
Jackson (for JSON)
Kryo (a fast, compact binary serialization format)
Smile (a binary format that comes with Jackson 1.6 and later).
Java Object Serialization.
We experimented with other serializers recently:
SimpleXML seems solid, runs at 2x the speed of XStream, but requires a bit too much configuration for our situation.
YamlBeans had a couple of bugs.
SnakeYAML had a minor bug relating to dates.
Jackson JSON, Kryo, and Jackson Smile were all significantly faster than good old Java Object Serialization, by about 3x to 4.5x. XStream is on the slow side. But these are all solid choices at this point. We'll keep monitoring the other three.
http://x-stream.github.io/ is nice, please take a look at it! Very convenient
of which implementation we don't have any control
The solution is don't do this. If you don't have control of a type's implementation you shouldn't be serialising it. End of story. Java serialisation provides serialVersionUID specifically for managing serialisation incompatibilities between different versions of a type. If you don't control the implementation you cannot be sure that IDs are being changed correctly when a developer changes a class.
Take a simple example of a 'Point'. It can be represented by either a cartesian or a polar coordinate system. It would be cost prohibitive for you to build a system that could cope dynamically with these sorts of corrections - it really has to be the developer of the class who designs the serialisation.
In short it's your design that's wrong - not the technology.
The easiest thing for you to do is still to use serialization, IMO, but put more thought into the serialized form of the classes (which you really ought to do anyway). For instance:
Explicitly define the SerialUID.
Define your own serialized form where appropriate.
The serialized form is part of the class' API and careful thought should be put into its design.
I won't go into a lot of details, since pretty much everything I have said comes from Effective Java. I'll instead, refer you to it, specifically the chapters about Serialization. It warns you about all the problems you're running into, and provides proper solutions to the problem:
http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683
With that said, if you're still considering a non-serialization approach, here are a couple:
XML marshalling
As many has pointed out is an option, but I think you'll still run into the same problems with backward compatibility. However, with XML marshalling, you'll hopefully catch these right away, since some frameworks may do some checks for you during initialization.
Conversion to/from YAML
This is an idea I have been toying with, but I really liked the YAML format (at least as a custom toString() format). But really, the only difference for you is that you'd be marshalling to YAML instead of XML. The only benefit is that that YAML is slightly more human readable than XML. The same restrictions apply.
google came up with a binary protocol -- http://code.google.com/apis/protocolbuffers/ is faster, has a smaller payload compared to XML -- which others have suggested as alternate.
One of the advanteages of protocol buffers is that it can exchange info with C, C++, python and java.
Try serializing to json with Gson for example.
Also a very fast JDK serialization drop-in replacement:
http://ruedigermoeller.github.io/fast-serialization/
If serialization speed is important to you then there is a comprehensive benchmark of JVM serializers here:
https://github.com/eishay/jvm-serializers/wiki
Personally, I use Fame a lot, since it features interoperability with Smalltalk (both VW and Squeak) and Python. (Disclaimer, I am the main contributor of the Fame project.)
Possibly Castor?
Betwixt is a good library for serializing objects - but it's not going to be an automatic kind of thing. If the number of objects you have to serialize is relatively fixed, this may be a good option for you, but if your 'customer' is going to be throwing new classes at you all the time, it may be more effort than it's worth (Definitely easier than XMLEncoder for all the special cases, though).
Another approach is to require your customer to provide the appropriate .betwixt files for any objects they throw at you (that effectively offloads the responsibility to them).
Long and short - serialization is hard - there is no completely brain dead approach to it. Java serialization is as close to a brain dead solution as I've ever seen, but as you've found, incorrect use of the version uid value can break it. Java serialization also requires use of the marker 'Serializable' interface, so if you can't control your source, you are kind of out of luck on that one.
If the requirement is truly as arduous as you describe, you may have to resort to some sort of BCE (Byte code modification) on the objects / aspects / whatever. This is getting way outside the realm of a small development project, and into the realm of Hibernate, Casper or an ORM....
SBE is an established library for fast, bytebuffer based serialization library and capable of versioning. However it is a bit hard to use as you need to write length wrapper classes over it.
In light of its shortcomings, I have recently made a Java-only serialization library inspired by SBE and FIX-protocol (common financial market protocol to exchange trade/quote messages), that tries to keep the advantages of both while overcoming their weaknesses. You can take a look at https://github.com/iceberglet/anymsg
Another idea: Use cache. Caches provide much better control, scalability and robustness to the application. Still need to serialize, though, but the management becomes much easier with within a caching service framework. Cache can be persisted in memory, disk, database or array - or all of the options - with one being overflow, stand by, fail-over for the other . Commons JCS and Ehcache are two java implementations, the latter is an enterprise solution free up to 32 GB of storage (disclaimer: I don't work for ehcache ;-)).
Related
I'm new to this Apache Avro(serialization framework). I know what serialization is but why there are separate frameworks lik avro, thrift, protocol buffers and
Why cant we use java serialization api's instead of these separate frameworks, are there any flaws in java serializatio api's.
What is the meaning of below phrase
"does not require running a code-generation program when a schema changes" in avro or in any other serializatio framework.
Please help me to understand all these!!
Why cant we use java serialization api's instead of these separate frameworks, are there any flaws in java serializatio api's.
I would assume you can use Java Serialization unless you know otherwise.
The main reasons not to use it are
you know there is a performance problem.
you need to exchange data across languages. Java Serialization is only for Java.
does not require running a code-generation program when a schema changes
I am guessing this means it can read serialized data with an older or newer model without having to re-generate and compile the code. i.e. it is tolerant of changes in the model.
BTW: As the data models I work with are usually a) very simple b) require maximum performance, I write my own Serialization without using a framework (or write my own framework) This is fine provided your model is very simple and won't change often.
In short, unless you know you can't, try Java Serialization first.
A comparison I did on different Serialization Methods
1.
The problem with java serialization is that it's not agnostic of your code. Meaning that is tightly coupled to the structure of you classes. Other serialization frameworks provide you with some flexibility/control that it's useful to bypass this kind of situations. Even though there is a way in java standard mechanism to control serialization through the writeObject readObject methods, it is a problem that other fwks have addressed in a more elegant way.
Second, you cannot interexchange the output of your java serialization with other language - platforms.
Last, but not least. Java serialization does not produce the more compact result possible, which might lead to performance degradation if you perform things like transfer data over a network. Other protocols (like Oracle's POF or protocol buffers) are more optimized to produce an smaller output.
2.
Regarding your second question I guess that what that means is that you don't need to run any precompile job that generates code in the case that the structure of your serialized classes changes. I personally hate frameworks that force some kind of compile-time code generation. I hate the hassle of having to even have to look at generated code, but that is just me and my ocd.
Two principle things Avro does well: Hadoop's MapReduce and communication protocol structures. I use it for MapReduce where I put numerous data instances in a single file all conforming to a particular schema; each record is stored very efficiently and markers delineate each individual record. Hadoop also uses it to communicate data between the Map and Reduce tasks. Much better than storing field names alongside data. These files are easy to split into multiple parts for processing in a distributed computing environment. Since the schema is embedded into the file, a reader doesn't have to know what the data looks like. Avro is not tied to any language and there are several language APIs for reading Avro data. If you want to write out a single complex object, then Java's serialization OR Avro will work. If you want more power and efficiency and are using millions of individual instances, then Avro is a good alternative. I am sure you can do this with the Java API, but why work that hard.
There are mechanisms to evolve schemas thru the schema resolution rules. There are also tools that will turn your java objects into schemas for you.
The best place to start is here: http://avro.apache.org/docs/current/spec.html It may take a couple of reads to get the gist. Read it again after trying to use some of the tools that come with the Avro package. Avro takes a while to get the hang of. JSON is only used as a data specification language it isn't used to store the data. You can generate schemas using the API or using a JSON file. Lots of flexibility and enough rope to easily get into trouble with -- well worth it tho.
We're looking for a way to serialize objects in Java that would be as fast and small as possible, but that will also allow us to change the classes as time progresses and still be able to read old object stored in the "old format".
The best thing we can come up with so far is Jackson. Any suggestions?
The native serialization supports that. See http://docs.oracle.com/javase/6/docs/platform/serialization/spec/version.html
I was warned against using Guava immutable collections in objects used in serialized communication because if the version of Guava on one end were updated, there could be serialization version incompatibility issues. Is this a valid concern?
Let's give some perspective.
The most prominent uses of serialization are:
storing data in between runs of your application
sending data between a client and a server
Guava is totally fine for application 2, if you control which Guava version is being used on both the client and the server. Moreover, while Guava doesn't make guarantees on the consistency of serialization between Guava versions...in reality, the serialized forms don't change very often.
On the other hand, let me give some perspective as to why Guava doesn't guarantee the consistency of serialized forms. I changed the serialized form of ImmutableMultiset between Guava releases 9 and 10, and the reason why was because I needed to refactor things so I could add ImmutableSortedMultiset to the immutable collections. You can see the change yourself here. Trying to do this same refactoring while keeping the serialized forms consistent would have almost certainly required additional awkward hacks, which are...pretty strongly against the Guava team's philosophy. (It might have been doable by a more expert programmer than myself, but I still claim it wouldn't have been trivial.) Guaranteeing serialization compatibility for the long term would have required staggering amounts of effort, as discussed in the above linked mailing list thread, Kevin stated:
Trying to provide for
cross-version compatibility made things a hundred times more difficult and
we gave up on it before Guava even started.
and Jared:
The underlying problem is still there: ensuring that the serialized forms
are compatible between all Guava versions. That was a goal of mine when
working towards Google Collections 1.0, but I abandoned that goal after
realizing its difficulty. Implementing and testing cross-version
compatibility wasn't worth the effort.
Finally, I'll point out that Guava gets used internally at Google all over the place and manages pretty well.
Yes, that is a valid concern.
From the Guava project homepage (http://code.google.com/p/guava-libraries/):
Serialized forms of ALL objects are subject to change. Do not persist these and assume they can be read by a future version of the library.
If you're using Java native serialization Guava is not a good choice.
I have the following scenario: I am using a very big external library in my Eclipse RCP application for a specific purpose.
At this point in time I am not sure if I may not have to replace this library in the future to another one (because it does not provide the necessary functionality or something like that). Also I have users using this library from day one so I would like to encapsulate the library, giving me at least a chance of changing the library in the future without the user noticing or having to change anything in their code.
Is there a simple way to encapsulate a whole library in some automated fashion?
Unless the part of the library's interface you are actually using is completely trivial, or standardized the way JSF or JAX-B are (in which case you don't need encapsulation) this is a completely wasted effort.
I can guarantee that if you have to switch to a different library, the encapsulation would prove worthless because the other library has different underlying concepts and usage patters that cannot be made to fit the existing ones.
I don't think that's possible, since the syntax and semantics of the library might be unique to some extent.
Sure, you could create proxies for all the classes and provide those, but that might require quite some work (writing a framework that scans the library) and that wouldn't guarantee you that exchanging the library would be easy.
Imagine the replacement would provide different methods and even use different semantics (to some extent). What if methods/fields etc. were missing in the replacement?
The best way to handle that would be to write an explicit wrapper and make the users use only that wrapper. This way you could restrict the API to the core concepts that are really needed. This still might not provide a good enough encapsulation however, based on what the library actually does.
Example:
For 3D programming you could use OpenGL or Direct3D. Both have somewhat different APIs but use the same core concepts. Thus you could create a wrapper for them that provides a unified API. That wrapper might then have to convert some data etc. (like making column-oriented matrics row-oriented and vice versa) but since the core concepts are the same, that should be doable.
However, you'd need to stick to the core concepts and couldn't use additional features. For example, Direct3D would also provide some more highlevel API (Direct3DX) which isn't provided by OpenGL.
Suppose I have a remote JAX-RS JSON API from a server running Tomcat. I want to access this API from a C/C++ client. Are there any tools available to make life easier for the C/C++ client, e.g. code generators? Or does anybody have a suggestion for an alternative?
I have never heard of such a tool. More to the point, I suspect that such a tool (a C / C++ generator for JSON) is impractical.
There are a number of reasons why. Some of the most significant ones are:
A key problem is that JSON doesn't have schemas. This means that an API generator would have to resort to looking at example messages and try to infer what fields to expect and what their types are. This can be difficult and even theoretically impossible in some cases.
In languages like Java and C#, there are straight-forward "right ways" to generate object APIs; e.g. the JavaBeans conventions. In C++ and especially C, the conventions are not there, and there are complicating issues like container protocols and memory management to deal with.
In languages like Java and C# are runtime type-safe, and have various language level mechanisms are provided that allow you to use dynamic programming to deal with the JSON's schema-less nature. For example, in Java you have reflection, proxy classes, dynamic code generation and dynamic code loading, all of which can help in dealing with JSON. In C and C++, these mechanisms are generally unavailable.
In short, if you are using C or C++, JSON libraries are as good as it will get.
FOLLOWUP
As a comment points out, this may be feasible to implement in the context of a specific JAX-RS-based server implementation. You'd need to get hold of the internal metadata, apply the JSON mapping to it, and generate C / C++ APIs from that. The problems are:
The generator implementation would be platform specific.
The C / C++ based client would not be able to cope with changes to the effective schema without regeneration of the APIs and corresponding client code changes. (By contrast, a JSON library-based solution can in theory be coded to deal with unexpected new attributes, etc)
You still have the container / memory management problem to deal with.
What you need is your choice of library for sending and receiving http requests, and a json parser. Nothing is going to generate code to make it easier for you because the idea of such an API is that it spits out JSON. The point of JSON is to go across language and transport barriers in a consistent way. A bit like XML, but simpler.
This question might interest you: what's the best json parser? JSON Spirit Looks like a particularly good article.
Now, as you're using REST, all you need is to communicate to the right urls. Done.
The final thing you want to decide is what libary to use for network communication. Boost would be many people's recommendation, I'm sure.