Java Reference
In-Depth Information
Listing4-23 declaredasmallutilityclassnamed ID forreturninguniquelonginteger
identifiers via ID 's getNextID() method. Because this method was not synchron-
ized,multiplethreadscouldobtainthesameidentifier. Listing6-5 fixesthisproblemby
including reserved word synchronized in the method header.
Listing 6-5. Returning unique identifiers in a thread-safe manner via synchronized
class ID
{
private static long nextID = 0;
static synchronized long getNextID()
{
return nextID++;
}
}
Although synchronized is appropriate for this class, excessive use of this re-
served word in more complex classes can lead to deadlock, starvation, or other prob-
lems. Listing 6-6 shows you how to avoid these assaults on a concurrent application's
liveness (theabilitytoexecuteinatimelymanner)byreplacing synchronized with
an atomic variable.
Listing 6-6. Returning unique IDs in a thread-safe manner via AtomicLong
import java.util.concurrent.atomic.AtomicLong;
class ID
{
private static AtomicLong nextID = new AtomicLong(0);
static long getNextID()
{
return nextID.getAndIncrement();
}
}
In Listing6-6 ,Ihaveconverted nextID froma long toan AtomicLong instance,
initializing this object to 0. I have also refactored the getNextID() method to
call AtomicLong 's getAndIncrement() method, which increments the Atom-
Search WWH ::




Custom Search