what is serialization and how it works [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why Java needs Serializable interface?
I know the serialization process but have't implemented it.
In my application i have seen there are various classes that has been implemented serilizable interface. consider following class
public class DBAccessRequest
implements Serializable
{
private ActiveRequest request = null;
private Connection connection = null;
private static Log log = LogFactory.getLog(DBAccessRequest.class);
public DBAccessRequest(ActiveRequest request,Connection connection)
{
this.request = request;
this.connection = connection;
}
/**
* #return Returns the DB Connection object.
*/
public Connection getConnection() {
return connection;
}
/**
* #return Returns the active request object for the db connection.
*/
public ActiveRequest getRequest() {
return request;
}
}
just setting request and connection in constructor and having getter setter for them.
so what is the use of serilizable implementation over here...

It's what is called a marker interface; it's used to define types that are serializable in Java. From the API:
java.io.Serializable: Serializability of a class is enabled by the class implementing [this] interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
See also:
Wikipedia/Marker interface pattern
Effective Java 2nd Edition, Chapter 11: Serialization.
Also Item 37: Use marker interface to define types.
Sun Developer Network Technical Article/Discover the secrets of the Java Serialization API

Layman would say : "Serializable? It's how to tell Java, that I need to breake this object to bytes and safely store somewhere else, and vice versa"

Serialization is more complicated then that, if you ever tried to save a few native variables like int, long, etc. into a stream you called them literally.
int i=100;
stream.write(i);
The thing about serialization, every Serializable object has a serialVersionUID that is unique to each object that is Serializable, and via reflection + a very sophisticated mechanizem (to prevent saving the same instance of an objects over again) it breaks down the object and saves it as bytes, just like my example, only there is a predefined very general mechanizem that does it.
which means, in your example it would look into the DBAccessRequest Class object check for which variable are there and if they are Serializable too it would perform the same process on them, and chop them to their Serializable core, and save them as bytes.
This is all metaphorical to explain the general concept of a process which is very complicates, very intresting and worth investigating (you should look it up also):
How Serialization works1
How Serialization works2
Hope this help,
Adam.

From Sun:
We all know the Java platform allows
us to create reusable objects in
memory. However, all of those objects
exist only as long as the Java virtual
machine1 remains running. It would be
nice if the objects we create could
exist beyond the lifetime of the
virtual machine, wouldn't it? Well,
with object serialization, you can
flatten your objects and reuse them in
powerful ways.
So I think that the reason why this is marked as serializable was that once that the JVM is up and running again, the data that was previously used is loaded and used again. This might be useful so as to avoid having the user enter the same data each and every time that the application loads.

Rozer, I guess you mean why the class is marked Serializable and no functionality related to serialization is put there except getters and setters.
The class might not directly implement the serializable functions.
The class which derives your DBAccessRequest class might implement them; or
The class which has an instance of DBAccessRequest might needed to be serialized which necessitate DBAccessRequest to be serializable.
I don't have any other explanation for this.

Related

Why doesn't Serializable interface contain any methods? [duplicate]

This question already has answers here:
Although the Serializable interface in Java has no methods, no fields, it can achieve its function. How?
(6 answers)
Closed 7 years ago.
I know what is serialization and why it is used, but my question:
Why is serialization a marker interface?
What is the potential benefit of not having writeObject, readObject in Serializable interface because when we do serialization we finally override these 2 methods?
How does readResolve ensure that the object created during deserialization is not the new object. I know the below and it is returning the same object during deserialization but who will call this readResolve method internally?
private Object readResolve() throws java.io.ObjectStreamException {
return INSTANCE;
}
Because there needs to be some explicit way of declaring a class to be serializable. The framework can't just assume all classes to be serializable, as there are many kinds of objects that will stop working if their fields are written to disk and are later reloaded from there (e.g. FileInputStream, which relies on an open operating system file handle which might no longer exist when the object is deserialized). The modern way of having such a declaration would be an annotation, but those didn't exist in Java at the time serialization was added.
You won't necessarily need to override them - if the default behavior of the serializer is good enough; you don't need to do anything but implement Serializable.
The serialization framework calls it when an object has been completely deserialized. At this time, the object is allowed to inspect its own contents, and if it decides that it should instead be represented by another instance, it can return that instance instead (if not, it returns this). Whatever comes out of this method is returned to the code that requested the deserialization. If a preexisting object was returned, the new object created by the deserializer will not be seen by anyone and will eventually be garbage collected.
Marker Interfaces are used to tell JVM to perform specific tasks. they don't have any method. Serializable is also a marker interface.
Serialization is the process of flattening the objects. when you implement serializable interface in a class, it tells JVM to serialize its object i.e. it has to be converted into stream.

RMI marshal and serialization

In java using RMI to marshal an object that you are returning from the remote class do you just need to implement Serializable on that object? I have a class node with variables inside that i want to be returned. Do i just implement serializable? If so what about the class that is receiving the object? does its class need to implement serializable too?
example:
public class node implements Serializable{
//variables
//variables
public node(//arguments to constructor here){
}
}
The class that is being serialized needs to implement Serializable. The sending and receiving classes don't. Not sure why you would think otherwise.
If you have a class whose instances you want to serialize using built-in Java serialization, not only must it implement Serializable, all its instance variables must also implement Serializable, or be primitives, or be marked transient (i.e. you tell the JVM that it's okay for them to not get serialized).
If your class can't conform to these constraints for some reason, you can implement custom serialization behavior yourself by implementing Externalizable - then you take responsibility for writing out your object's state and reading it back on the other end.
I'm not sure whether I understand your question correctly or not, but ... if the serializable class has other objects as member variables, then better make them serializable also, otherwise better declare as transient to skip. does this answer your question?
if code inspector program is handy, you can have answer for such question very quickly without posting it
for your tip, only the object you wan to persist or transfer needs to implements Serializable, so the object can be reconstructed as the class structure through serializing/unserializing

RMI serialization/marshal [duplicate]

This question already has answers here:
RMI marshal and serialization
(3 answers)
Closed 9 years ago.
I need some clarification on serialization in java. If i am serializing an object and i want to return that object over RMI do i just implement serializable on my object's custom class? I've seen objectoutputstream and objectinputstream but i don't know if i need to use those as i don't quite undersand their usage. My second question is how would i go about making an arraylist serializable? My third question is maybe related to my first question but how do i marshal an object before returning it? does serializing the object marshals it in the process?
Lets call the class in question Sentence:
public class Sentence implements Serializable {
}
And then i would be creating an instance of that class and returning that object from some other class
Yes: implementing Serializable makes your object serializable, unless it references an object that is not serializable. Object streams are used internally by RMI to send and receive objects. You don't need to use them if using RMI. If you want to send an object using sockets, or save it to a file, then you can use them.
ArrayList is already serializable. Look at its javadoc. You don't have to do anything.
You simply return the object from your RMI method, and RMI will serialize it for you. Serialization and marshalling are two words that basically mean the same thing. In the same way, if an RMI methods takes an argument, RMI will serialize the object passed as argument, send it to the RMI server, which will deserialize it and then call your actual method. It's all done for you by RMI.
Serializable is what's called a marker interface; it just tells Java that your class has some ability without requiring you to implement any particular methods. Implementing it in your class tells the JVM that it's okay (meaningful) to take the fields of your Java object and convert them to a packaged form for use later or on another computer.
That's all you have to do if all of the fields in your class are Serializable. If you have fields that aren't Serializable, such as fields that hold network connections or native resources, you'll need to mark them transient (ignored by serialization) and take care of setting them back up when your class is deserialized by overriding readObject and/or writeObject.

Java: What can and what can't be serialized?

If the Serializable interface is just a Marker-Interface that is used for passing some-sort of meta-data about classes in java - I'm a bit confused:
After reading the process of java's serialization algorithm (metadata bottom-to-top, then actual instance data top-to-bottom), I can't really understand what data cannot be processed through that algorithm.
In short and formal:
What data may cause the NotSerializableException?
How should I know that I am not supposed to add the implements Serializable clause for my class?
First of all, if you don't plan to ever serialize an instance of your class, there is no need to even think about serializing it. Only implement what you need, and don't try to make your class serializable just for the sake of it.
If your object has a reference (transitive or direct) to any non-serializable object, and this reference is not marked with the transient keyword, then your object won't be serializable.
Generally, it makes no sense to serialize objects that can't be reused when deserialized later or somewhere else. This could be because the state of the object is only meaningful here and now (if it has a reference to a running thread, for example), or because it uses some resource like a socket, a database connection, or something like that. A whole lot of objects don't represent data, and shouldn't be serializable.
When you are talking about NotSerializableException it is throw when you want to serialize an object, which has not been marked as Serializable - that's all, although when you extend non serializable class, and add Serializable interface it is perfectly fine.
There is no data that can't be serialized.
Anything your Serializable class has in it that is not Serializable will throw this exception. You can avoid it by using the transient keyword.
Common examples of things you can't serialize include Swing components and Threads. If you think about it it makes sense because you could never deserialize them and have it make sense.
All the primitive data types and the classes extend either Serializable directly,
class MyClass extends Serializable{
}
or indirectly,
class MyClass extends SomeClass{
}
SomeClass implements Serializable.
can be serialized. All the fields in a serializable class gets serialized except the fields which are marked transient. If a serializable class contains a field which is not serializable(not primitive and do not extend from serializable interface) then NotSerializableException will be thrown.
Answer to the second question : As #JB Nizet said. If you are going to write the instance of a class to some stream then and then only mark it as Serializable, otherwise never mark a class Serializable.
You need to handle the serialization of your own Objects.
Java will handle the primitive data types for you.
More info: http://www.tutorialspoint.com/java/java_serialization.htm
After reading the process of java's serialization algorithm (metadata bottom-to- top, then actual instance data top-to-bottom), I can't really understand what data cannot be processed through that algorithm.
The answer to this is certain system-level classes such as Thread, OutputStream and its subclasses which are not serializable. Explained very well on the oracle documents: http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html
Below is the abstract:
On the other hand, certain system-level classes such as Thread, OutputStream and its subclasses, and Socket are not serializable. Indeed, it would not make any sense if they were. For example, thread running in my JVM would be using my system's memory. Persisting it and trying to run it in your JVM would make no sense at all.
NotSerialisable exception is thrown when something in your serializable marked as serializable. One such case can be:
class Super{}
class Sub implements Serializable
{
Super super;
Here super is not mentioned as serializable so will throw NotSerializableException.
More practically, no object can be serialized (via Java's built-in
mechanism) unless its class implements the Serializable interface.
Being an instance of such a class is not a sufficient condition,
however: for an object to be successfully serialized, it must also be
true that all non-transient references it holds must be null or refer to
serializable objects. (Do note that that is a recursive condition.)
Primitive values, nulls, and transient variables aren't a problem.
Static variables do not belong to individual objects, so they don't
present a problem either.
Some common classes are reliably serialization-safe. Strings are
probably most notable here, but all the wrapper classes for primitive
types are also safe. Arrays of primitives are reliably serializable.
Arrays of reference types can be serialized if all their elements can be
serialized.
What data may cause the NotSerializableException?
In Java, we serialize object (the instance of a Java class which has already implemented the Serializable interface). So it's very clear that if a class has not implemented the Serializable interface, it cannot be serialized (then in that case NotSerializableException will be thrown).
The Serializable interface is merely a marker-interface, in a way we can say that it is just a stamp on a class and that just says to JVM that the class can be Serialized.
How should I know that I am not supposed to add the implements
Serializable clause for my class?
It all depends on your need.
If you want to store the Object in a database, you can
serialize it to a sequence of byte and can store it in the
database as persistent data.
You can serialize your Object to be used by other JVM working
on different machine.

Why does implementing Externalizable need a default public constructor?

We don't need it if we're implementing Serializable. So why this difference? How does it relate to the actual mechanism of Serialization?
A thorough explanation (although the grammar of the article might be improved) can be found on http://www.jusfortechies.com/java/core-java/externalization.php . The short answer, for future reference in case the linked page goes away:
Externalizable is an interface extending Serializable. Contrary to Serializable, though, objects are not restored by just reading the serialized bytestream, but the public constructor is called and only once the object is thus created, its state is restored. This makes restoring more efficient.
Edit: See also What is the difference between Serializable and Externalizable in Java? .
This is primarily used for caching purposes. In order to deserialize across streams, you will need to spell out how you want your object to be deserialized, hence the two methods provided by the contract in Externalizable interface: writeExternal and readExternal. Note that Externalizable extends Serializable, so you don't necessarily need to implement Serializable interface (although it's a marker interface and there are no methods to be actually implemented).
For a sample implementation, have a look at MimeType.
A public no-arg constructor is needed while using Externalizable interface.
Because in case of Serializable
readObject reads the required information from the ObjectInputStream
Serialization uses reflection mechanism to get the necessary fields and their corresponding values.
Serializable serializes all the data members (except static and transient).
But in case of Externalizable
No reflection mechanism used.
User doesn't serializes all data members.That's why to fetch values of the members which are not externalized public no arg constructor is required.

Categories