Java Reference
In-Depth Information
After the server acquires a socket channel, it creates an
inputStream
by calling
Channels.newInputStream(socket)
and then wrapping that input stream
with an
ObjectInputStream
. The server then proceeds to loop and read each ob-
ject coming from the
ObjectInputStream
. If the object received's
toString()
method equals
EOF
, the server stops looping and the connection is closed.
Note
Using an
ObjectOutputStream
and
ObjectInputStream
to send and
receive a lot of objects can lead to memory leaks.
ObjectOutputStream
keeps a
copy of the sent object for efficiency. If you were to send the same object again,
Ob-
jectOutputStream
and
ObjectInputStream
will not send the same object
again, but instead send a previously sent Object ID. This behavior or just sending the
Object ID instead of the whole object raises two issues.
The first issue is that objects that are changed in-place (mutable) will not get the change
reflected in the receiving client when sent through the wire. The reason is that because
the object was sent once, the
ObjectOutputStream
believes that the object is
already transmitted and will only send the ID, negating any changes to the object that
have happened since it was sent. To avoid this, don't make changes to objects that were
sent down the wire. This rule also applies to sub-objects from the object graph.
The second issue is that because
ObjectOutputStream
maintains a list of sent ob-
jects and their Object IDs, if you send a lot of objects the dictionary of sent objects to
keys grows indefinitely, causing memory starvation on a long-running program. To alle-
viate this issue, you can call
ObjectOutputStream.reset()
, which will clear
the dictionary of sent objects. Alternatively, you can invoke
ObjectOut-
putStream.writeUnshared()
to not cache the object in the
ObjectOut-
putStream
dictionary.
8-5. Obtaining the Java Execution Path
Problem
You want to get the path where the Java program is running.
Solution