Consider Using Byte Arrays to Store Marshalling Results

Marshalling converts an object graph into a set of bytes. The bytes are usually simply pushed into a stream and sent over a wire (or to a file or database). But there’s no reason why another level of indirection can’t be inserted into the process, as in the following code example:

public class SerializeIntoBytes implements Externalizable {
	private byte[] _bytes;
	public void writeExternal(ObjectOutput out) throws IOException {
		if (null == _bytes) {
			createByteArray(  );

	public void readExternal(ObjectInput in) throws IOException, 
ClassNotFoundException {
		int byteArrayLength = in.readInt(  );
		_bytes = new byte[byteArrayLength];;
		restoreStateFromByteArray(  );

	protected void createByteArray(  )  {
	// The "real" marshalling goes on in here.

	protected void restoreStateFromByteArray(  ) {
	// The "real" demarshalling goes on in here.

The first thing this idiom does is enable you to reuse the end result of marshalling an object more than once. Consider, for example, the following scenario:

A client application makes a remote method call to an authentication server and receives an authentication key which will expire in two hours. For the next two hours, whenever the client application makes a call to a back-end server, it passes in the authentication key to prove that it is authorized to make the method call.

The authentication key in this scenario has two crucial features: ...

Get Java Enterprise Best Practices now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.