2

I have a class "A" with method "calculate()". Class A is of type singleton(Scope=Singleton).

public class A{ 

public void calculate(){
   //perform some calculation and update DB
 }

}

Now, I have a program that creates 20 thread. All threads need to access the method "calculate()". I have multicore system. So I want the parallel processing of the threads.

In the above scenario, can i get performance? Can all threads access the method calculate at same instance of time?

Or, Since the class A is singleton so, the threads needs to be blocked waiting.

I have found similar questions in the web/Stackoverflow. But I cannot get clear answer. Would you please help me?

5
  • Are instances of A thread safe? Is the method synchronized? Commented Jun 10, 2013 at 4:22
  • A singleton that holds state need to be synchronized.... Commented Jun 10, 2013 at 4:22
  • Yes, instance of A is thread safe. Since, class A is singleton, only one instance of Class A is created in whole life of program. Commented Jun 10, 2013 at 4:26
  • Milan, just wondering if it's a conventional "Java Singleton class" or an enum or you are using dependency injector frameworks like Spring or Guice to control the scope? Commented Jun 10, 2013 at 4:45
  • Any method needs synchronizing if it changes the object state that can be accessed by more than one thread at a time. The fact that the object is a singleton has nothing to do with it. Commented Jun 10, 2013 at 5:49

5 Answers 5

3

Statements like "singletons need synchronization" or "singletons don't need synchronization" are overly simplistic, I'm afraid. No conclusions can be drawn only from the fact that you're dealing with the singleton pattern.

What really matters for purposes of multithreading is what is shared. If there are data that are shared by all threads performing the calculation, then you will probably need to synchronize that access. If there are critical sections of code than cannot run simultaneously between threads, then you will need to synchronize that.

The good news is that often times it will not be necessary to synchronize everything in the entire calculation. You might gain significant performance improvements from your multi-core system despite needing to synchronize part of the operation.

The bad news is that these things are very complex. Sorry. One possible reference:

http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601/ref=sr_1_1?ie=UTF8&qid=1370838949&sr=8-1&keywords=java+concurrency+in+practice

Sign up to request clarification or add additional context in comments.

Comments

2

That's the fundamental concept of Singleton. Only one instance of the class would be present in the system (JVM). Now, it depends on the implementation of calculate(). Is it a stateless utility method? If yes, you might not want to make it synchronized. In that case, multiple threads will be able to access it at the same instance of time. If calculate() is NOT stateless, i.e. it uses instance variables (and those instance variables will be used by multiple threads), then be careful; You have to make calculate() thread safe. You have to synchronize the method. At least you have to use a synchronize block inside the method. But, once you do so, only one thread will be able to access it (the synchronized block or the synchronized block inside the method) at any point of time.

public void calculate() {

    //Some code goes here which does not need require thread safety.
    synchronized(someObj) {
        //Some code goes here which requires thread safety.
    }
    //Some code goes here which does not need require thread safety.
}

If you want to use parallel processing (if that's the primary goal), then singleton is not the design pattern that you should use.

1 Comment

stateless is good point, adding to this point, consider having critical section problem, for example, bank transactions. It is possible that the user can initiate multiple transactions simultaneously. Here state doesn't come into picture.
1

I have found similar questions in the web/Stackoverflow. But I cannot get clear answer.

There is a good reason for that!!

It is not possible to say whether a method on a singleton does, or does not, need to be synchronized by virtue of being singleton.

Synchronization and the need for synchronization is all about state that may be shared by different threads.

  • If different threads share state (even serially), then synchronization is required.

  • If not then no synchronization is required.


The only clues that you have provided us that would help us give you a yes / no answer are this enigmatic comment:

  // perform some calculation and update DB

... and the fact that the calculate() method takes no arguments.

If we infer that the calculate() method gets its input from the state of the singleton itself, then at least the part of the method (or the methods it calls) must synchronize while retrieving that state. However, that doesn't mean that the entire method call must be synchronized. The proportion of its time that the calculate method needs to hold a lock on the shared data will determine how much parallelism you can actually get ...

The updating of the database will also require some kind of synchronization. However, this should be taken care of by the JDBC connection object and the objects you get from it ... provided that you obey the rules and don't try to share a connection between multiple threads. (The database update will also present a concurrency bottleneck ... assuming that the updates apply to the same database table or tables.)

Comments

0

It depends on how you implement Singleton. If you use Synchronized keyword then they will wait else not. Use Singleton with eager initialization.

Something like this:

public final class Universe {

  public static Universe getInstance() {
     return fINSTANCE;
  }

  // PRIVATE //

  /**
  * Single instance created upon class loading.
  */
  private static final Universe fINSTANCE =  new Universe();

  /**
  * Private constructor prevents construction outside this class.
  */
  private Universe() {
    //..elided
  }
} 

Above will perform very well in multithreaded environment. or else you can go for enum implementation of Singleton.

Check this link for various singleton implementation: http://javarevisited.blogspot.in/2012/07/why-enum-singleton-are-better-in-java.html

2 Comments

Does it gives performance in multicore environment. Parallel execution of threads in multicore?
It's a solution for accessing the singleton instance. It doesn't answer the OP's question about whether calculate() needs to be synchronized.
0

Multiple threads can invoke calculate() at the same time.

Those invocations won't be queued (executed serially) within that JVM unless you perform some type of concurrency control (making the method synchronized is one option).

The fact that your object is a singleton may or may not affect performance, depending on how that object's attributes (if any) are used within calculate().

Also bear in mind that since you are "updating DB", table or row level locks may also limit concurrency.

If you are worried about performance, the best bet is to test it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.