Singletons and multithreading question
Hi, I had a class created as a singleton as it was only used in one place. However since Ive now multithreaded the part of the program that calls the singleton code so it could be called twice at the same time.
If the method being called initializes all its variables within the method, is that method safe to be called in a mutli-threaded env or not ?
If it in my situation all variables are declared within the method except a precompiled javax.xml.XPathExpression class, the same one is used to parse an Input Source, the input source itself is created within the method. I
think I am having concurrency problems , (SAXParser Exceptions) and I think it is because of this XPathExpression class but cannot clearly understand why.
What is the correct solution, I dont want to initilize the XPathExpression within the method because the method is called many times always for the same expression, dropping the singleton and creating new instances of the class on every call would be even worse. I require multithreading to improve concurrency is there a safe Multi Singleton pattern that i should be using ?
# 4
There are two issues:
a) is the singleton object safe for multithreaded use
b) how do I safely create a singleton in a multi-threaded application
The answer to (a) depends on the class. It sounds from your description that you are using an object (the XPathExpression) that might not be thread-safe. I can't tell you if it is or not. Assuming it is not you either need to synchronize this method so that all threads will go through it (and use the expression) one at a time - which may defeat the purpose of multi-threading - or else you need a way to use multiple instances of these expressions in different threads. As I'm not familiar with these classes I can't tell you what you can and can't do concurrently.
There are a number of answers to (b). Construction via static initialization is the simplest and safest. If you want lazy initialization and the class that holds the reference to the singleton must be loaded even if the singleton isn't needed, then lookup the initialize-on-demand-holder-class idiom (see Josh Bloch's "Effective Java" item 48)
# 6
As stated in the documentation for javax.xml.xpath.XPathExpression (http://java.sun.com/javase/6/docs/api/javax/xml/xpath/XPathExpression.html), it is not thread-safe.
So as you suggest one approach would really be to have an instance of the expression per thread. Instances can be kept in a private static java.lang.ThreadLocal (http://java.sun.com/javase/6/docs/api/java/lang/ThreadLocal.html).
In my opinion this would be better than the 'Multiton' example code.