Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

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.

share|improve this answer
    
Methods do not have instances. In Java, that is. –  Deiwin Aug 10 '12 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. –  Martijn Verburg Aug 10 '12 at 8:32
1  
Good points; I've incorporated them into the answer. –  Michael Borgwardt Aug 10 '12 at 8:36
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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