Re: Singleton and performance
Manish Pandit wrote:
On Nov 28, 8:53 am, sen...@gmail.com wrote:
What is the behavior/performance in concurrent access environment for
the following:
SingletonClass {
//no state. Only its own instance.
method() {
//do this
//do that
//send request to a queue
//read from dynamic queue
//return data
}
}
NormalClass {
//some member variables
method() {
//do this
//do that
//send request to a queue
//read from dynamic queue
//return data
}
}
Scenario 1:
---------------
SomeClass {
some method() {
SingletonClass s = SingletonClass.getInstance();
Data data = s.method();
}
}
Scenario 2:
---------------
SomeClass {
some method() {
NormalClass s = new NormalClass();
Data data = s.method();
}
}
Assumption: the method that reads data from queue can take a while to
finish. Each queue request results response in a dynamic queue.
Will Singleton cause a performance bottleneck by serializing
execution?
With the structures above, none of the approaches appear thread-safe.
To achieve thread safety, you will need to synchronize the method, or
synchronize on an object's lock in the code fragment that needs to be
thread safe. Thread safety will cause a performance bottleneck in
multi-threaded environment as it impacts concurrent execution.
The "queue" could be a class from java.util.concurrent such as
<http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html>
This might obviate the need for 'synchronized'.
Concurrent programs don't have to experience "a performance bottleneck" to be
safe. If that were the case, there'd be no use case for concurrent
programming. In fact, well-designed thread-safe concurrent code will increase
performance in many cases. Even more importantly, it can decouple application
modules from each other, and actually reduce the chance for bugs.
Assuming you do program with thread safety in mind, of course.
Use of API classes such as ConcurrentLinkedQueue simplifies one's job and
decreases risk because we're using standard and (presumably) robust libraries.
--
Lew