Last active
August 29, 2015 14:01
-
-
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...)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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