T
- The type to recycle.E
- An exception type that can be thrown while acquiring an instance of the type to recycle.AutoCloseable
public abstract class Recycler<T extends AutoCloseable,E extends Exception> extends Object implements AutoCloseable
// Autoclose the Recycler when last instance has been released
try (Recycler<ZipFile, IOException> recycler = new Recycler<>() {
@Override
public ZipFile newInstance() throws IOException {
return new ZipFile(zipFilePath);
}
}) {
// Repeat the following as many times as needed, on as many threads as needed
try {
ZipFile zipFile = recycler.acquire();
try {
// Read from zipFile -- don't put recycler.acquire() in this try block, otherwise the
// finally block will try to release the zipfile even when recycler.acquire() failed
// [...]
} finally {
recycler.release(zipFile);
zipFile = null;
}
} catch (IOException e) {
// May be thrown by recycler.acquire()
}
}
Constructor | Description |
---|---|
Recycler() |
Modifier and Type | Method | Description |
---|---|---|
T |
acquire() |
Acquire or allocate an instance.
|
void |
close() |
Call this only after all instances have been released.
|
abstract T |
newInstance() |
Create a new instance.
|
void |
release(T instance) |
Release/recycle an instance.
|
public void release(T instance)
instance
- The instance to release.public void close()
close
in interface AutoCloseable
Copyright © 2018. All rights reserved.