2D Volatile arrays: will self-assignment help or do I need AtomicIntegerArray?

十年热恋 提交于 2019-12-01 13:50:39

You do need atomicity because writing to an array is a non-atomic process. Specifically, Java will certainly never guarantee that writes to array members will stay invisible to other threads until you choose to publish them.

One option is to create a new array each time, fully initialize it, and then publish over a volatile, but this may incur a significant cost due to Java's insistence that a newly allocated array must be first zeroed out, and due to GC overhead. You may overcome this with a "double buffering" scheme where you keep just two arrays and switch between them. This approach has its dangers: a thread may still be reading from the array which your writing thread has already marked as the inactive one. This highly depends on the precise details of your code.

The only other option is to do the whole reading and writing in a classic, boring, synchronized block. This has the advantage of being very predictable in latency. Personally, I'd start from this and move on to anything more complicated if absolutely pressed by an actual performance issue.

You could also lock using read-write locks, but this would only pay off if multiple threads read the array concurrently. This does not seem to be your case.

Have a look at java.util.concurrent.ArrayBlockingQueue.

When you call take() on a blocking queue, it will automatically wait until something is made available.

Simply place the byte[] onto the queue and the consumer will process it. The need to know how many buffers are to be processed is irrelevant in this scenario. Usually, a "terminate" item in the queue would represent the last buffer. It would help to wrap the byte[] in a class with a boolean terminate flag.

Regards Yusuf

In addition to @Marko Topolnik explained above about how volatile and atomic works, if you still want to achieve the effect for across-thread visibility when writing into array, you can use Unsafe.putLongVolatile(), Unsafe.putObjectVolatile() and all other methods in the same family.

Yes it's not that Java like but it resolves your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!