0

We can realize mutual exclusion in java with a lock (intrinsic lock or ReentrantLock) :

Lock lock = new ReentrantLock();
  try {
            lock.lock();
           //do something
            }
        } finally {
            lock.unlock();
        }

or with a Semphore(1)

  Semaphore semaphore = new Semaphore(1);
        try {
            semaphore.acquire();
            //do soemthing
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }

I see that the advantage of a semaphore here that it puts threads in WAITING state, but a lock puts threads in BLOCKED state (BLOCKED puts more stress on scheduler). fromThisAnswer

Is it considered a bad practice to use semaphore for mutual exclusion? Should we always favor locks for mutual exclusion?

Siri
  • 97
  • 10
  • a `Lock` makes more sense here, if you want mutual exclusion. – Eugene May 01 '20 at 03:18
  • *"BLOCKED puts more stress on scheduler"* Why do you say that? According to [this answer](https://stackoverflow.com/a/35943544/5221149): "WAITING threads and BLOCKED threads do not use CPU resources at all". – Andreas May 01 '20 at 03:24
  • @Andreas according to this [answer](https://stackoverflow.com/questions/15680422/difference-between-wait-and-blocked-thread-states), Blocked puts more stress on scheduler, as it is contending for the lock so scheduler counts it as a thread he has to service. – Siri May 01 '20 at 03:47
  • @Siri The answer that says that is talking about `notifyAll()`, so it's not applicable to your case. Semaphore has more overhead than Lock, so use Lock. – Andreas May 01 '20 at 04:09
  • Ignore that 'stress on scheduler' stuff. – Martin James May 01 '20 at 05:21
  • @MartinJames ignore it because it is wrong or because it doesn't have a strong impact? – Siri May 01 '20 at 06:29

0 Answers0