Yes it works. But it works horribly.
It happens before it works only when the release of the writer occurs before the acquisition of the reader. In your implementation, it is assumed that everything you write will be completed before further reading / updating with ThreadB . Due to the fact that your data will be red all the time synchronized, this will cause performance problems, although, as far as I can not say for sure. Of course, you made your synchronization more granular, have you tested it already?
The best solution is to use the singleton / single-user singleton / transfer SPSC queue (single producer / single consumer) to store the current snapshot of the message flow and use it with every update.
int[] data = ... Queue<int[]> queue = new ... // Thread A while (true) { for (1000 iterations or so) { ... } queue.add(data); } // Thread B while (true) { int[] snapshot = queue.take(); this.repaint(); }
The advantage of this is that you do not need to do busywait, you can just wait until the queue is locked or until the next recording. You can skip entries that you do not have time to update. You do not need to depend on an arbitrary thread scheduler to schedule data flows for you.
Remember that thread-safe data structures are great for transferring data between streams.
Edit: oops, I forgot to say that depending on how your updates go, you can use a copy of the array so that your data is not distorted from random entries that are not cached.
xTrollxDudex
source share