public class CloseableResource<T>
extends java.lang.Object
implements java.lang.AutoCloseable
AutoCloseable
that wraps a resource that needs to be cleaned up but does not implement
AutoCloseable
itself.
Recipients of a CloseableResource
are in general responsible for cleanup. Ownership
can be transferred from one context to another via transfer()
. Transferring relinquishes
ownership from the original resource. This allows resources to be safely constructed and
transferred within a try-with-resources block. For example:
try (CloseableResource<Foo> resource = CloseableResource.of(...)) {
// Do something with resource.
...
// Then transfer ownership to some consumer.
resourceConsumer(resource.transfer());
}
Not thread-safe.
Modifier and Type | Class and Description |
---|---|
static class |
CloseableResource.CloseException
An exception that wraps errors thrown while a resource is being closed.
|
static interface |
CloseableResource.Closer<T>
A function that knows how to clean up after a resource.
|
Modifier and Type | Method and Description |
---|---|
void |
close()
Closes the underlying resource.
|
T |
get()
Gets the underlying resource.
|
static <T> CloseableResource<T> |
of(T resource,
CloseableResource.Closer<T> closer)
Creates a
CloseableResource with the given resource and closer. |
CloseableResource<T> |
transfer()
Returns a new
CloseableResource that owns the underlying resource and relinquishes
ownership from this CloseableResource . |
public static <T> CloseableResource<T> of(T resource, CloseableResource.Closer<T> closer)
CloseableResource
with the given resource and closer.public T get()
public CloseableResource<T> transfer()
CloseableResource
that owns the underlying resource and relinquishes
ownership from this CloseableResource
. close()
on the original instance
becomes a no-op.public void close() throws CloseableResource.CloseException
close
in interface java.lang.AutoCloseable
CloseableResource.CloseException
- wrapping any exceptions thrown while closing