# Concurrent byte array access in Java with different locking

I have one writer thread and 10 reader threads of a byte array. It is important to synchronize writes and reads over a "row" (16 bytes).

There are a lot less locks than rows, e.g. in the current configuration 1024 (chunkRows) rows have one lock which makes the overall operation faster, but also consumes less memory.

Here is the read method for ReadWrite locking:

public void read(int pointer, byte[] tmpBytes, int length) {
Lock lock = locks[pointer / rowSize / chunkRows].readLock();
lock.lock();
try {
System.arraycopy(bytes, pointer, tmpBytes, 0, length);
} finally {
lock.unlock();
}
}


and here for simple "Object"-synchronized:

public void read(int pointer, byte[] tmpBytes, int length) {
Object lock = locks[pointer / rowSize / chunkRows];
synchronized (lock) {
System.arraycopy(bytes, pointer, tmpBytes, 0, length);
}
}


Here is the full repository which you can easily run via maven. It uses JMH to avoid nasty performance pitfalls. Of course, also write is synchronized similarly.

Now why is my ReadWrite implementation a lot slower than synchronized? (RW is roughly 40% slower)

I like Object-locking more because it uses less RAM but did I made a mistake with ReadWrite-locking or does this make sense?

I tried it on my dual core laptop as well as on more beefy quad core commodity server with simmilar results (Object-locking faster than RW). I get something like 13.0 ops/s for ReadWrite locking and 21.6 ops/s for Object locking.

Update

Several things were wrong in the benchmark which I fixed (maybe there are still glitches)

• Very important bug fix was to include service.awaitTermination
• make sure write and read happen at the same time and both are long enough (previously write was too short and nearly no r+w concurrency happened)
• I've learned about StampedLock, could be slightly faster and also optimistic locking could be even the winner here.
• minor thing: catch errors in runnable otherwise they won't appear

See all in this commit

• Welcome to Code Review and good job on your first post! Though I still think that there's a simple answer to this that would be likely to get answered on StackOverflow instead, no? Please also update the title to reflect what the code is supposed to do, not what you want to be answered. Sep 7, 2016 at 15:50
• Thanks ferada. I fear on SO they say it is more related to code review ... we'll see if I can get a satisfying answer. Regarding the title: do you have an example? Sep 7, 2016 at 16:25
• I've updated it, but perhaps you can make it more accurate. Sep 7, 2016 at 17:17
• BTW: There could be a more memory efficient solution, which I go through in this question: stackoverflow.com/q/39675003/194609 Sep 24, 2016 at 11:39