... until the collector arrives ...

This "blog" is really just a scratchpad of mine. There is not much of general interest here. Most of the content is scribbled down "live" as I discover things I want to remember. I rarely go back to correct mistakes in older entries. You have been warned :)

2006-12-13

Copy a Java Serializable

I'm tired of repeatedly recreating this code to copy a Java Serializable:

private static <OBJECT_TYPE extends Serializable> OBJECT_TYPE copySerializable(
        OBJECT_TYPE object) {
    try {
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
        ObjectOutputStream objectOutput = new ObjectOutputStream(byteOutput);
        objectOutput.writeObject(object);
        ByteArrayInputStream byteInput = new ByteArrayInputStream(byteOutput.toByteArray());
        ObjectInputStream objectInput = new ObjectInputStream(byteInput);
        @SuppressWarnings("unchecked")
        OBJECT_TYPE copy = (OBJECT_TYPE) objectInput.readObject();
        return copy;
    } catch (Exception ex) {
        throw new RuntimeException(String.format("unable to copy the object '%s'", object), ex); //$NON-NLS-1$
    }
}

or its threaded equivalent that uses pipes:

private static <OBJECT_TYPE extends Serializable> OBJECT_TYPE copySerializable2(
        final OBJECT_TYPE object) {
    try {
        final PipedInputStream pipeInput = new PipedInputStream();
        final PipedOutputStream pipeOutput = new PipedOutputStream(pipeInput);
        Thread writerThread = new Thread("copySerializable2") { //$NON-NLS-1$
            @Override
            public void run() {
                try {
                    ObjectOutputStream objectOutput = new ObjectOutputStream(pipeOutput);
                    try {
                        objectOutput.writeObject(object);
                    } finally {
                        objectOutput.close();
                    }
                } catch (IOException ex) {
                    throw new RuntimeException(String.format(
                        "Unable to serialize the object '%s'", object), ex); //$NON-NLS-1$
                }
            }
        };
        writerThread.start();
        try {
            ObjectInputStream objectInput = new ObjectInputStream(pipeInput);
            try {
                @SuppressWarnings("unchecked")
                OBJECT_TYPE copy = (OBJECT_TYPE) objectInput.readObject();
                return copy;
            } finally {
                objectInput.close();
            }
        } finally {
            writerThread.join();
        }
    } catch (Exception ex) {
        throw new RuntimeException(String.format("Unable to read the object '%s'", object), ex); //$NON-NLS-1$
    }
}

Blog Archive