In a library in Java 7, I have a class which provides services to other classes. After creating an instance of this service class, one method of it may be called several times (lets call it the doWork() method). So I do not know when the work of the service class is completed. The problem is the service class uses heavy objects and it should release them. I set this part in a method (lets call it release()), but it is not guaranteed that other developers will use this method.Is there a way to force other developers to call this method after completing the task of service class? Of course I can document that, but I want to force them.Note: I cannot call the release() method in the doWork() method, because doWork()  needs those objects when it is called in next.
Force other developers to call method after completing their work
java
The pragmatic solution is to make the class AutoCloseable, and provide a finalize() method as a backstop (if appropriate ... see below!).  Then you rely on users of your class to use try-with-resource or call close() explicitly.Of course I can document that, but I want to force them.Unfortunately, there is no way1 in Java to force the programmer to do the right thing.  The best you could hope to do is to pick up incorrect usage in a static code analyser.On the topic of finalizers.  This Java feature has very few good use cases.  If you rely on finalizers to tidy up, you run into the problem that it can take a very long time for the tidy-up to happen.  The finalizer will only be run after the GC decides that the object is no longer reachable.  That may not happen until the JVM does a full collection.Thus, if the problem you are tying to solve is to reclaim resources that need to be released early, then you have missed the boat by using finalization.And just in case you haven't got what I am saying above ... it is almost never appropriate to use finalizers in production code, and you should never rely on them!1 - There are ways.  If you are prepared to hide the service objects from user code or tightly control their lifecycle (e.g. https://softwareengineering.stackexchange.com/a/345100/172) then the users code doesn't need to call release().  However, the API becomes more complicated, restricted ... and ugly IMO.  Also, this is not forcing the programmer to do the right thing.  It is removing the programmer's ability to do the wrong thing!