O'Reilly logo

PURE Java™ 2 by Kenneth Litwak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required