Java Reference
In-Depth Information
public static Factory getFactory()
{
if (factory == null)
{
factory = new Factory();
// ...
}
return factory;
}
CHALLENGE 8.2
Why might you decide to lazy-initialize a singleton instance rather than initialize it
in its field declaration?
Singletons and Threads
If you want to lazy-initialize a singleton in a multithreaded environment, you have to take
care to prevent multiple threads from initializing the singleton. In a multithreaded
environment, a method is not guaranteed to run to completion before a method in another
thread starts running. This opens the possibility, for example, that two threads will try to
initialize a singleton at roughly the same time. Suppose that a method finds that a singleton is
null. If another thread begins executing at that moment, it will also find that the singleton is
null. Then both methods will proceed to initialize the singleton. To prevent this sort of
contention, you need a locking ability to help coordinate methods running in different threads.
The Java language and class libraries include good support for multithreaded development. In
particular, Java supplies every object with a monitor —a lockable aspect that represents
possession of the object by a thread. To ensure that only one thread initializes a singleton, you
can synchronize the initialization on the monitor of a suitable object. Other methods that
require exclusive access to the singleton can synchronize on the same monitor. Concurrent
Programming in Java™ (Lea 2000) suggests synchronizing on the monitor that belongs to the
class itself:
package com.oozinoz.machine;
public class Factory_2 {
private static Factory_2 factory;
private static final Object
classLock = Factory_2.class;
private long wipMoves;
private Factory_2()
{
wipMoves = 0;
}
Search WWH ::




Custom Search