Home » Java » Core Java » Speed Up with Fast Java and File Serialization

About Jakub Kubrynski

I'm software developer by vocation. Java team leader at work and open source enthusiast at home. Strongly interested in new technologies. Fan of java.util.concurrent and sun.misc.Unsafe. My motto is "minimum code, maximum functionality.

Speed Up with Fast Java and File Serialization

Since the first version of Java, day-by-day many developers have been trying to achieve at least as good of performance as in C/C++. JVM vendors are doing their best by implementing some new JIT algorithms, but there is still a lot to do, especially in how we use Java.

For example, there is a lot to win in objects<->file serialization – notably in writing/reading objects that can readily fit in the memory. I’ll try to shed some light on that topic.

All the tests were executed on the simple object shown below:
 

public class TestObject implements Serializable {
  private long longVariable;
  private long[] longArray;
  private String stringObject;
  private String secondStringObject; //just for testing nulls

  /* getters and setters */
}

To be more concise I’ll show only the write methods (though the other way is quite similar, too). Full source code is available on my GitHub (http://github.com/jkubrynski/serialization-tests).

The most standard java serialization (that we all start from) looks like this:

public void testWriteBuffered(TestObject test, String fileName) throws IOException {
  ObjectOutputStream objectOutputStream = null;
  try {
    FileOutputStream fos = new FileOutputStream(fileName);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    objectOutputStream = new ObjectOutputStream(bos);
    objectOutputStream.writeObject(test);
  } finally {
    if (objectOutputStream != null) {
      objectOutputStream.close();
    }
  }
}

The easiest way to speed up the standard serialization is to use the RandomAccessFile object:

public void testWriteBuffered(TestObject test, String fileName) throws IOException {
  ObjectOutputStream objectOutputStream = null;
  try {
    RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
    FileOutputStream fos = new FileOutputStream(raf.getFD());
    objectOutputStream = new ObjectOutputStream(fos);
    objectOutputStream.writeObject(test);
  } finally {
    if (objectOutputStream != null) {
      objectOutputStream.close();
    }      
}

The more sophisticated technique is to use the Kryo framework. The difference between the old and the new version is vast. I’ve checked both. Because the performance comparison doesn’t show any spectacular dissimilarities, I’ll focus on the second version as it’s much more user-friendly and even somewhat faster.

private static Kryo kryo = new Kryo(); // version 2.x

public void testWriteBuffered(TestObject test, String fileName) throws IOException {
  Output output = null;
  try {
    RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
    output = new Output(new FileOutputStream(raf.getFD()), MAX_BUFFER_SIZE);
    kryo.writeObject(output, test);
  } finally {
    if (output != null) {
      output.close();
    }
  }
}

The last option is a solution inspired by Martin Thompson’s article. It shows how to play with the memory in the C++ way and in the Java

public void testWriteBuffered(TestObject test, String fileName) throws IOException {
  RandomAccessFile raf = null;
  try {
    MemoryBuffer memoryBuffer = new MemoryBuffer(MAX_BUFFER_SIZE);
    raf = new RandomAccessFile(fileName, "rw");
    test.write(memoryBuffer);
    raf.write(memoryBuffer.getBuffer());
  } catch (IOException e) {
    if (raf != null) {
      raf.close();
    }
  }
}

TestObject write method is shown below:

public void write(MemoryBuffer unsafeBuffer) {
  unsafeBuffer.putLong(longVariable);
  unsafeBuffer.putLongArray(longArray);
  // we support nulls
  boolean objectExists = stringObject != null;
  unsafeBuffer.putBoolean(objectExists);
  if (objectExists) {
    unsafeBuffer.putCharArray(stringObject.toCharArray());
  }
  objectExists = secondStringObject != null;
  unsafeBuffer.putBoolean(objectExists);
  if (objectExists) {
    unsafeBuffer.putCharArray(secondStringObject.toCharArray());
  }
}

Direct memory buffer class (shortened, just to show the idea):

public class MemoryBuffer {
  // getting Unsafe by reflection
  public static final Unsafe unsafe = UnsafeUtil.getUnsafe();

  private final byte[] buffer;

  private static final long byteArrayOffset = unsafe.arrayBaseOffset(byte[].class);
  private static final long longArrayOffset = unsafe.arrayBaseOffset(long[].class);
  // other offsets 

  private static final int SIZE_OF_LONG = 8;
  // other sizes 

  private long pos = 0;

  public MemoryBuffer(int bufferSize) {
    this.buffer = new byte[bufferSize];
  }

  public final byte[] getBuffer() {
    return buffer;
  }

  public final void putLong(long value) {
    unsafe.putLong(buffer, byteArrayOffset + pos, value);
    pos += SIZE_OF_LONG;
  }

  public final long getLong() {
    long result = unsafe.getLong(buffer, byteArrayOffset + pos);
    pos += SIZE_OF_LONG;
    return result;
  }

  public final void putLongArray(final long[] values) {
    putInt(values.length);
    long bytesToCopy = values.length << 3;
    unsafe.copyMemory(values, longArrayOffset, buffer, byteArrayOffset + pos, bytesToCopy);
    pos += bytesToCopy;
  }

  public final long[] getLongArray() {
    int arraySize = getInt();
    long[] values = new long[arraySize];
    long bytesToCopy = values.length << 3;
    unsafe.copyMemory(buffer, byteArrayOffset + pos, values, longArrayOffset, bytesToCopy);
    pos += bytesToCopy;
    return values;
  }

  /* other methods */
}

Results of many hours of the Caliper’s runs are shown below:

Full trip [ns]Standard deviation [ns]
Standard2073072362
Standard on RAF42661733
KRYO 1.x12027112
KRYO 2.x11479259
Unsafe855491

In the end we can draw a few conclusions:

  • Unsafe serialization is greater than 23 times faster than standard use of java.io.Serializable
  • Use of RandomAccessFile can speed up standard buffered serialization by almost 4 times
  • Kryo-dynamic serialization is about 35% slower than the hand-implemented direct buffer.

Finally, as we can see, there is still no golden hammer. For a lot of us, gaining 3000 ns (0.003ms) is not worth writing custom implementations for every object we want to serialize with files. And for standard solutions we’ll mostly choose Kryo. Nevertheless, in low-latency systems, where 100ns seems like an eternity, the choice will be completely different.
 

Reference: Speed Up with Fast Java and File Serialization from our JCG partner Jakub Kubrynski at the Java(B)Log blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

2 comments

  1. what about using Externalizable interface instead of Serializable and using Direct memory buffer technique?

  2. That’s a bit lukewarm comparision.
    Generic Serialization will write the class names and check for double references.

    Set Kryo to “unshared mode” to get better results. Preregister classes to avoid writing classnames.
    Also note there are faster full compatible implementaions of the JDK-serialization like https://github.com/RuedigerMoeller/fast-serialization.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


7 + = eight

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close