?
Solved

Java - How to make a project multi-thread safe

Posted on 2005-04-07
10
Medium Priority
?
276 Views
Last Modified: 2012-08-13
hi all,

i have ready lot of documentation to make a project multi-thread safe. But I am not able to apply this in the project i have got. this project has been developed and is being used. but I have been told to see if this can be made multi-thread safe.

here is the thing,

there are certain service classes that is being used by users.

we have USER1 and USER 2 in same JVM.
they create Service as below by calling getInstance
which is as below

    public static ChargeCalculationService getInstance()
                  throws ChargeCalculationServiceException
                                                                    
      {      if (ccs == null)
            {      ccs = new ChargeCalculationService();
            }
            return ccs;
      }
      
and then doStuff in this instance.


But User 1 does a ChargeCalculationService.getInstance and performing some operation
and in between User 2 came in and do ChargeCalculationService.getInstance .. and it gets User 1 instance and starts perfoming operation and may interfere with each other..

Then there is lot of other classes which are singletons and also we have static variables which might be overwritten.

I am not sure but looks like I have to make changes in all the places (which is not a quick fix).

I want to quick fix and a best fix.

If I synchronize this service getInstance method, will it fix the issue.

I am planning to use as below:

public static Singleton getInstance() {
  if (_instance == null) {
    synchronized(Singleton.class) {
      if (_instance == null)
        _instance = new Singleton();
    }
  }
  return _instance;
}


Will it fix my issue? and if yes how?


Thanks,
I really appreciate it.

0
Comment
Question by:narrav
  • 4
  • 2
  • 2
8 Comments
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 13731799
would seem easier to just synchronize the whole method, you're not getting much advantage from just synchronizing that block

 public static synchonized ChargeCalculationService getInstance()
               throws ChargeCalculationServiceException
                                                         
     {     if (ccs == null)
          {     ccs = new ChargeCalculationService();
          }
          return ccs;
     }

It fixes the problem with that method because now only one thread will be able to call that method at one time.
0
 
LVL 19

Assisted Solution

by:Jim Cakalic
Jim Cakalic earned 500 total points
ID: 13732151
Hi,

Because of the Java memory model, singletons should not be constructed using the Double-Checked Locking (DCL) strategy. What objects suggested will work because it forces a synchronization on the method invokation as opposed to only when the singleton reference was found to be null. Better yet would be to construct the singleton instance as part of class initialization as in:

public class ChargeCalculationService {
    private static final ChargeCalculationService _instance = new ChargeCalculationService();

    public static ChargeCalculationService getInstance() {
        return _instance;
    }
}

This neatly bypasses the whole synchronization problem since the JVM won't allow method calls until the class has loaded and been initialized and that includes construction of the singleton instance.

For more on why DCL is bad: http://www.javaworld.com/javaworld/jw-05-2001/jw-0525-double.html

Ultimately, though, you can't make a singleton out of something that isn't thread-safe (unless I misunderstood your example). There's no quick fix way to thread safety. For more info on that topic: http://www.javaworld.com/jw-08-1998/jw-08-techniques.html

Best regards,
Jim Cakalic
0
 
LVL 92

Expert Comment

by:objects
ID: 13732176
> There's no quick fix way to thread safety.

Yes, the above is only fixing the problem with that method.
You'll still need to make the rest of your code thread safe.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:narrav
ID: 13739330
Objects/Jim,

Before we go further on my issue, I have a more general question..

This is a project where we need to develop a generic API used by many applications and in each appl's, many users.

Do you think to create this kind of API, we should be implementing singelton in our API at all?
This API has been developed by singleton already. But isn't this wrong?

Singelton should be implemented by the users of API, not by an API.. isn't this right??

0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 13739983
Not sure what you mean by "Singleton should be implemented by the users of the API." Do you mean that, if an object needs what appears to be a singleton to accomplish it's responsibilities then whoever constructs the object is responsible for providing the reference to the "singleton"?

Remember the synopsis of Singleton is: "Ensure a class has only one instance, and provide a global point of access to it." Any other use of Singleton is really an abuse, not a use. At least, that's an opinion espoused here
    http://www-106.ibm.com/developerworks/webservices/library/co-single.html

It seems that Singletons are being heavily overused these days as a means to prevent object instantiation. If you are developing a service-oriented API then it might not be wrong use a Singleton implementation to prevent multiple instantiations of the service provider class. The article referenced above goes into some of the critieria you might consider and different aspects on your design problem that might lead to an efficient yet non-traditional approach to this problem.

Sorry that doesn't seem like much help at the moment.
0
 

Author Comment

by:narrav
ID: 13740870
Jim,

I meant that Singleton should be implemented by the user who wants to use my Generic API.

My generic api is service oreinted but it be used by many application and then each appl. has many users.

And these many appl. can be in one JVM or different JVM's.

So what I mean is -- these applications - while they create an instance of object from my api should implement singleton for their application rather than I maintaining singletons from them .. isn't this correct?

Like example - we use Java Api from sun to build our code.. now sun doesn't implement singleton on their end, we as users implement singleton whle creating java api instances if we need to..  right??

sorry, just trying to understand!!
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 13755504
You might be right. I don't know enough about your application or environment to respond for or against. However, to the extent that you are developing an API you are going to be specifying something about how users access the API. If there is no reason why you should force users down the singleton path then why do it? Allow clients to construct instances and make all your methods instance methods. If, in fact, there is a need for pooling or restricting to a single  instance then that can be provided by others means: a specific pooling class, JNDI registration and lookup, etc.
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 14588352
OK
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month13 days, 18 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question