-1

How to avoid method execution from multiple threads if they pass same parameter. for example I have this method:

public void sync(int x){    

    //sync code -> write code here which is eligible for sync
}

If this method is running with parameter x=5 and another request with same value x=5 comes, it should be added in queue.

Community
  • 1
  • 1
M1r1
  • 197
  • 2
  • 10
  • Basically this is **way too broad**. As in: there is no *simple* mechanism to do this. If you really have to **serialize** multiple threads on a parameter, then a single method taking an int parameter won't do. Because then you first have to design a solution with those multiple queues. – GhostCat Feb 12 '18 at 09:20
  • You can is BlockingQueue , which is there in java.util.concurrent package – Ramesh Fadatare Feb 12 '18 at 09:25

2 Answers2

3

You can use name-based lock.

public void sync(int x){
    Lock lock = new NameBasedLock(String.valueOf(x));
    lock.lock();
    try {
        doSomething();
    } finally {
        lock.unlock();
    }
}
xingbin
  • 27,410
  • 9
  • 53
  • 103
0

You can use simply

   public synchronized void sync(int x){
       //Body of method

}

spandey
  • 1,034
  • 1
  • 15
  • 30
  • This avoid execution of sync method from multiple threads,but i want to avoid execution of a method only when it is passed same parameter – M1r1 Feb 14 '18 at 23:10