Java serialization, ObjectInputStream.readObject(), check if will block

前端 未结 4 1772
别跟我提以往
别跟我提以往 2020-12-03 16:14

I\'m using an ObjectInputStream to call readObject for reading in serialized Objects. I would like to avoid having this method block,

相关标签:
4条回答
  • 2020-12-03 16:39

    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.

    0 讨论(0)
  • 2020-12-03 16:49

    The BufferedInputStream works for me, and why not just check if(bis.available() > 0) instead of a N value, this works perfectly for me. I think ObjectInputStream.readObject blocks(= waits until) when no input is to be read. So if there is any input at all in the stream aka if(bis.available() > 0) ObjectInputStream.readObject will not block. Keep in mind that ObjectInputStream.readObject might throw a ClassNotFoundException, and that is't a problem at all to me.

    0 讨论(0)
  • 2020-12-03 16:54

    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.

    0 讨论(0)
  • 2020-12-03 16:59

    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.

    0 讨论(0)
提交回复
热议问题