Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save adohe-zz/5d17f1f9b45c05a59cbb to your computer and use it in GitHub Desktop.

Select an option

Save adohe-zz/5d17f1f9b45c05a59cbb to your computer and use it in GitHub Desktop.
A singleton implementation through double-check with auto-close support(this could be useful for thread pool or connection pool etc...)
public abstract class Lazy<T> implements AutoCloseable {
private volatile T instance = null;
protected abstract T makeObject();
protected abstract void destroyObject(T obj);
public T get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = makeObject();
}
}
}
return instance;
}
@Override
public void close() throws Exception {
synchronized (this) {
if (instance != null) {
T instance_ = instance;
instance = null;
destroyObject(instance_);
}
}
}
}
// A possible usage maybe this
private static Lazy<ScheduledThreadPoolExecutor> timer_ = new Lazy<ScheduledThreadPoolExecutor>() {
@Override
protected ScheduledThreadPoolExecutor makeObject() {
return new ScheduledThreadPoolExecutor(2);
}
@Override
protected void destroyObject(ScheduledThreadPoolExecutor timer) {
timer.shutdown();
try {
while (!timer.awaitTermination(1, TimeUnit.SECONDS)) {/**/}
} catch (InterruptedException e) {/**/}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment