Java – How to we handle multiple instances of a method through a single class instance

concurrencyjava

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?

Best Answer

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.