2

How can we handle multiple instances of a method through a single class instance(Single constructor call)?

To elaborate, I have a handler class which has two methods lets say verifyUser(String JSON) and getUserInfo(String JSON). Assuming that there are many users accessing this methods, there will be multiple instances of these methods. The handler class should be initialized once. I.e. multiple objects of this class are not permitted, rather multiple method instances are allowed.

What will be the ideal solution for enabling concurrent method calls without corrupting data while executing?

2 Answers 2

10

In Java, methods do not have instances. The correct terminology is that there will be multiple threads executing methods on the same object.

There are basically three ways to do this without risking data corruption:

  • Share no mutable data between the threads, i.e. have no mutable fields in the class.
  • Protect all mutable shared data by using synchronization so that only one thread at a time can access it.
  • Use special lock-free algorithms or data structures, like those found in the java.util.concurrent package.

In any case, doing this correctly is hard in any but the most trivial cases. You really need to understand what can go wrong in order to avoid it. Java Concurrency in Practice is an excellent book you could use to achieve that understanding.

3
  • Methods do not have instances. In Java, that is.
    – Deiwin
    Commented Aug 10, 2012 at 8:27
  • 1
    I recommend reading Java Concurrency in Practice to get a handle on all of the edge cases and best practices when dealing with concurrency. Commented Aug 10, 2012 at 8:32
  • 1
    Good points; I've incorporated them into the answer. Commented Aug 10, 2012 at 8:36
0

As long as you don't create any member variables in this class that would be modified by these methods, you should be safe. But in this case can also consider declaring these methods as static.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.