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?