> If multiple threads are going to access the logger, you'll need
> appropriate synchronization constructs to ensure that the singleton
> can't get instantiated more than once. This is non-trivial, but a
> solution is available. Google for it, but beware that there is a
The solution is quite trivial - assign the logger during class
initialisation.
private static final Logger self = new Logger();
> decent amount of inaccurate advice out there on this topic. In
> particular, the double-checked locking pattern is flawed and should not
> be used.
You can use it in 1.5. Almost certainly it will be a pointless waster of
time and confuse people. Just need to make the reference volatile. In
practice this should also work in 1.4.
private static volatile Logger self;
public static Logger getInstance() {
if (self == null) {
// WORKS FROM 1.5, BUT NOT RECOMMENDED.
synchronized (Logger.class) {
if (self == null) {
self = new Logger();
}
}
}
return self;
}
> I ran into this issue last year and used it as a jumping-off point to
> learn a lot about Java synchronization. I heartily endorse Doug Lea's
> book on the topic. It was one of the best technical books I've read in
> years. It will make you feel smart, so read it.
Yup.
Concurrent Programming in Java: Design Principles and Patterns, Doug Lea
http://www.amazon.co.uk/exec/obidos/ASIN/0201310090/
Tom Hawtin

Signature
Unemployed English Java programmer
http://jroller.com/page/tackline/
Aray - 03 Jan 2006 15:54 GMT
Thanks Luke Meyers and Thomas Hawtin indicating my bugs
"Thomas Hawtin" <usenet@tackline.plus.com>
??????:43ba667a$0$1468$ed2619ec@ptn-nntp-reader01.plus.net...