Object in Java have what CLTL terms indefinite extent:
Indefinite extent. The entity continues to exist as long as the possibility of reference remains.
The (im)possibility of reference in Java is determined by the Garbage Collector (GC) asynchronously, at some undermined time after the possibility of reference changes. As discussed previously in C++/SWIG/Java/RAII post and JAVA/RAII post this makes it difficult to implement semantics similar to RAII in C++.
Since Java 7, it is possible to create objects which hold resources that have dynamic extent using the try-with-resources statement. Dynamic extent is defined CLTL as:
Dynamic extent. References may occur at any time in the interval between establishment of the entity and the explicit disestablishment of the entity. As rule, the entity is disestablished when execution of the establishing construct completes or is otherwise terminated. Therefore entities with dynamic extent obey a stack-like discipline, paralleling the nested executions of their establishing constructs.
Broadly speaking, a resource acquired in the
parenthesis will be released in a well-defined order1 promptly after
the completion of the
try-block. For this to happen, the
resource should be acquired in the initialiser and released in the
close() method of the
interface. There is a tutorial example
approach parallels RAII when using “local” or “statement”-scoped
objects to manage the resources. It is however less general than
managing resources using reference-counted smart-pointers in C++.
In those situations the closest mechanism in Java is the Cleaner which in turn uses the notification on status of references mechanism. Note however that release in this case is only “Some time after” rather than prompt.
Some time after the garbage collector determines that the reachability of the referent has changed to the value corresponding to the type of the reference, it will clear the reference and add it to the associated queue.
In reverse order to their initalisation/acquisition ↩