Search code examples
javaserializationdeserializationehcacheobjectinputstream

ObjectInputStream.read() returning -1, but readObject returns the object


Am to serialize an object and deserialize the object but I get:

  1. 0 for available()
  2. -1 for read()
  3. EOFException for readByte()

    public static Element getCacheObject(String key, String cacheName, String server) throws IOException, ClassNotFoundException, ConnectException {
        String url = StringUtils.join(new String[] { server, cacheName, key}, "/");
        GetMethod getMethod = new GetMethod(url);
        ObjectInputStream oin = null;
        InputStream in = null;
        int status = -1;
        Element element = null;
        try {
            status = httpClient.executeMethod(getMethod);
            if (status == HttpStatus.SC_NOT_FOUND) { // if the content is deleted already               
                return null;
            }
            in = getMethod.getResponseBodyAsStream();
            oin = new ObjectInputStream(in);
            System.out.println("oin.available():" + oin.available()); // returns 0
            System.out.println("oin.read():" + oin.read()); // returns -1
            element = (Element) oin.readObject(); // returns the object
        }
        catch (Exception except) {
            except.printStackTrace();
            throw except;
        }
        finally {
            try {
                oin.close();
                in.close();
            }
            catch (Exception except) {
                except.printStackTrace();
            }
        }
    
        return element;
    }
    

What am I missing here?


Solution

  • I think you see this behaviour because you first create ObjectInputStream from InputStream and only then check available on InputStream. If you check constructor of ObjectInputStream you can see following:

    public ObjectInputStream(InputStream in) throws IOException {
        verifySubclass();
        bin = new BlockDataInputStream(in);
        handles = new HandleTable(10);
        vlist = new ValidationList();
        enableOverride = false;
        readStreamHeader();
        bin.setBlockDataMode(true);
    } 
    

    There is a method readStreamHeader that reads header from input stream. So it is possible that all data is read from InputStream during construction of ObjectInputStream.