Using Synchronization
When there are multiple Threads running in a JVM, it is possible that multiple Threads will want to modify the same resource (object) at the same time. The simplest way to illustrate this is with the classic producer-consumer model. Imagine an array of float primitives:
float[] fltArray = new float[6];
This creates an array for holding six float primitives. In the producer-consumer model, a Thread, t1, tries to add floats to this array as fast as it can. Another Thread, t2, the consumer, tries to read and remove those floats as fast as it can. Typically, some kind of counter would be used to track which slot in the array last had a float put in it or taken from it. Listing 11.3 shows an unsynchronized (dangerous) way ...
Get PURE Java™ 2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.