Concurrent Programming in Java™: Design Principles and Pattern, 2nd Edition

Author: Douglas Lea
3.9
All Stack Overflow 13

Comments

by anonymous   2017-08-20

Conceptually you are looking for a Semaphore (which initialized with one permit, behaves equivalent to a Mutex).

If you cannot use J2SE 5.0, then I would suggest to check out it's predecessor util.concurrent, which is in Public Domain and can be backported/used on Java versions before J2SE 5.0 (I have used some derived classes on limited devices as well).

Take a look at the Semaphore and it's order providing derivative classes, e.g. FIFOSemaphore.

If you need guidance and a reference for the bookshelf, I recommend "Concurrent Programming in Java", by Doug Lea, who was responsible for util.concurrent and the JSR that brought us java.util.concurrent.

by anonymous   2017-08-20

Quoting Synchronization and the Java Memory Model from Concurrent Programming in Java by Doug Lea:

Changes to fields made by one thread are guaranteed to be visible to other threads only under the following conditions:

  • A writing thread releases a synchronization lock and a reading thread subsequently acquires that same synchronization lock.

  • If a field is declared as volatile, any value written to it is flushed and made visible by the writer thread before the writer thread performs any further memory operation (i.e., for the purposes at hand it is flushed immediately). Reader threads must reload the values of volatile fields upon each access.

  • The first time a thread accesses a field of an object, it sees either the initial value of the field or a value since written by some other thread.

  • As a thread terminates, all written variables are flushed to main memory. For example, if one thread synchronizes on the termination of another thread using Thread.join, then it is guaranteed to see the effects made by that thread (see §4.3.2).

Last two options do not apply to your situations so you need either volatile or synchronized, sorry. Note that AtomicInteger.get() simply returns volatile value, so you get nothing except extra layer.