0

I have multiple synchronized static methods in a class.

 public class DoSomething {
    public static synchronized void fun1()  {
            /*do something time consuming*/
    }

    public static synchronized void fun2()  {
            /*do something time consuming*/
    }
    .
    .
 }

Right now only one thread is allowed to execute any of the synchronized function in the class. Which is not efficient because the functions are independent of each other and can be run parallelly. How can can I make them independent of each other but only one thread is allowed per method with minimal changes to class.

Mohd Waseem
  • 1,244
  • 2
  • 15
  • 36

1 Answers1

4

Use separate objects to lock:

    private static final lock1=new Object();
    private static final lock2=new Object();

    public static void fun1()  {
       synchronized(lock1) {
            /*do something time consuming*/
       }
    }
    public static void fun2()  {
       synchronized(lock2) {
            /*do something time consuming*/
       }
    }
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • Thanks for the answer. This is one way to do it. But then whats the purpose of having multiple synchronized method in a class? Also if I make them non static and use Class objects to access, then which approach is better? How they are different in this context? – Mohd Waseem May 14 '20 at 16:53
  • Multiple synchronized non-static methods will ensure only one thread modifies the instance state. A static synchronized method already locks using the Class object. – Burak Serdar May 14 '20 at 16:57