Do I need to Dispose a SemaphoreSlim?

If you access the AvailableWaitHandle property, then Yes, you must call Dispose() to cleanup unmanaged resources. If you do not access AvailableWaitHandle, then No, calling Dispose() won’t do anything important. SemaphoreSlim will create a ManualResetEvent on demand if you access the AvailableWaitHandle. This may be useful, for example if you need to wait on multiple … Read more

CountDownLatch vs. Semaphore

CountDownLatch is frequently used for the exact opposite of your example. Generally, you would have many threads blocking on await() that would all start simultaneously when the countown reached zero. final CountDownLatch countdown = new CountDownLatch(1); for (int i = 0; i < 10; ++ i) { Thread racecar = new Thread() { public void … Read more

What is mutex and semaphore in Java ? What is the main difference?

Unfortunately everyone has missed the most important difference between the semaphore and the mutex; the concept of “ownership“. Semaphores have no notion of ownership, this means that any thread can release a semaphore (this can lead to many problems in itself but can help with “death detection”). Whereas a mutex does have the concept of … Read more

When should we use mutex and when should we use semaphore

Here is how I remember when to use what – Semaphore: Use a semaphore when you (thread) want to sleep till some other thread tells you to wake up. Semaphore ‘down’ happens in one thread (producer) and semaphore ‘up’ (for same semaphore) happens in another thread (consumer) e.g.: In producer-consumer problem, producer wants to sleep … Read more

tech