views:

1278

answers:

3

I'm using an ObjectInputStream to call readObject for reading in serialized Objects. I would like to avoid having this method block, so I'm looking to use something like Inputstream.available().

InputStream.available() will tell you there are bytes available and that read() will not block. Is there an equivalent method for seriailzation that will tell you if there are Objects available and readObject will not block?

+1  A: 

No. Although you could use the ObjectInputStream in another thread and check to see whether that has an object available. Generally polling isn't a great idea, particularly with the poor guarantees of InputStream.available.

Tom Hawtin - tackline
+1  A: 

The Java serialization API was not designed to support an available() function. If you implement your own object reader/writer functions, you can read any amount of data off the stream you like, and there is no reporting method.

So readObject() does not know how much data it will read, so it does not know how many objects are available.

As the other post suggested, your best bet is to move the reading into a separate thread.

David Crawshaw
A: 

I have an idea that by adding another InputStream into the chain one can make availability information readable by the client:

HACK!

InputStream is = ... // where we actually read the data
BufferedInputStream bis = new BufferedInputStream(is);
ObjectInputStream ois = new ObjectInputStream(bis);

if( bis.available() > N ) {
  Object o = ois.readObject();
}

The tricky point is value of N. It should be big enough to cover both serialization header and object data. If those are varying wildly, no luck.

Vladimir Dyuzhev
If they vary at all, then you can lose big. If you choose an N that is bigger than the next object, then you might get into a deadlock state where you're waiting for more than the current object, and the sender won't send the next object until you respond to the previous one. Better ensure that there's an unending supply of inputs before using this approach!
PanCrit