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.
Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

One Response to "Speed Up with Fast Java and File Serialization"

  1. Alonso says:

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

Leave a Reply


eight + 4 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books