Create ObjectOutputStream Before ObjectInputStreamIf you are writing code that transmits data bidirectionally using ObjectInputStream and ObjectOutputStream, be careful to construct the ObjectOutputStream first.
If you instead construct the ObjectInputStream first, both ends will
block and eventually fail in the constructor. This is because the
input stream constructor waits for an initial string of bytes to
arrive from the ObjectOutputStream
If your exception handling allows communications to proceed after constructing the input stream fails, then the symptoms of this problem are that both sides block for a period of time, one gets the exception and proceeds to construct the ObjectOutputStream. The other end then is able to construct its ObjectInputStream, since the initialization sequence just arrived.
Fortunately the fix is straightforward. Move the creation of the ObjectOutputStream before that of the ObjectInputStream. Then each end will transmit the initialization sequence before trying to open its input stream. The initialization sequence is ready and waiting, so the construction of the input stream goes normally, and object transfers can then commence without any delay.
Copyright © 2020 Andrew Oliver