Java Reference
In-Depth Information
But what does our client, the
StatRecorderImpl
, get when it makes a successful call to the
getRoster()
method? Not surprisingly, it gets just what the
StatRecorderImpl
sends, which
is a
LinkedList
of
PlayerImpl
objects. What may be surprising is what is required for that
simple answer to be the case. Getting a
LinkedList
is easy, as the
LinkedList
class is part
of the Java platform, and therefore is available on any machine running a compliant Java
runtime. But making sure that the
PlayerImpl
object can be made available to the
StatRe-
corderImpl
is somewhat more interesting. RMI could simply require that all of the types used
by clients and servers be present (and the same) on all machines running those clients and
servers. But this requires a form of coordination that is difficult to scale. Instead, RMI uses
object serialization to ensure that what you send is what you get.
To see how this works, let's look at how our
PlayerImpl
objects are sent from one virtual
machine to another. Our
PlayerImpl
class, it will be recalled, was declared as:
public class PlayerImpl implements Player, Serializable {
We declared this as
Serializable
so that
PlayerImpl
objects could be written to a file by
the
writeObject()
method of an
ObjectOutputStream
. While the
writeObject()
method
is specified as taking an
Object
parameter, the documentation tells us that the method will
throw a
NotSerializableException
if the method tries to write something that is not
Seri-
alizable
. Note that
NotSerializableException
is an extension of
IOException
, which
is already declared as a possible exception generated from
writeObject()
. So it does not
have to be declared as an additional part of the signature of the method, and the code catching
the
IOException
will also catch the
NotSerializableException
. If you want to handle the
NotSerializableException
separately, you can do so (but be sure that you catch that excep-
tion before catching the
IOException
), but you won't be required to do so by the compiler.
This is probably a design flaw, but there is nothing we can do about it now, other than make
sure that our code will catch this.
Making a class of objects serializable is generally as simple as declaring the class to imple-
ment the interface
java.io.Serializable
. This is a marker interface, like
Remote
, so there
are no methods that have to be implemented in a class that implements this interface. Instead,
saying that a class implements
Serializable
simply indicates that the automatic object seri-
alization mechanism can be applied to that object.
When object serialization was first designed as part of RMI, all Java objects were going to be
Serializable
by default. However, it was decided that this was a bad idea for a couple of