In .NET framework, System.Threading.Semaphore is an IDisposable that requires manually invoking dispose. However, in JavaSE, java.util.concurrent.Semaphore is not a Closeable nor an AutoCloseable.

Why do they choose different API design? Which one is better?

  • 2
    In my opinion managed objects that hold unmanaged resources shouldn't be disposable when those resources are cheap. But I don't think the .net framework designers agree with that point of view. Oct 16, 2016 at 9:18

2 Answers 2


In Java, a Semaphore is implemented entirely in Java. This means there is no native resource to clean up once it is not longer needed. It can be cleaned up like normal Java objects.

In Java, Closeable is needed where there is a native resource which is associated with the on heap Java object. e.g. file Streams or Sockets. These external resources are more expensive and limited than objects on the heap and could run out long before a GC is triggered and has cleaned them up.

Note: a GC is not enough to clean up these resource, the background thread closing them also has to run to free those resources. In HotSpot/JVM there is a Finalizer thread which closes these resources and if a few are slow to close it can lead to resource starvation.


Peter Lawrey explained it pretty well from a Java perspective, but there's a bit more to it for C# / Windows.

There is a limit on the number of handles that can be open at one time, and while the Garbage Collector should collect the Semaphores and run their finalizers, that is not guaranteed. The handles are released when the process ends, but that could take a long time.

Also, Semaphores can be used without .NET. It would be a little strange for C# to be unable to close the handles when C++ can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.