|
|
@@ -0,0 +1,66 @@
|
|
|
+/*
|
|
|
+ * @author Ranides Atterwim <ranides@gmail.com>
|
|
|
+ * @copyright Ranides Atterwim
|
|
|
+ * @license WTFPL
|
|
|
+ * @url http://ranides.net/projects/assira
|
|
|
+ */
|
|
|
+package net.ranides.assira.io;
|
|
|
+
|
|
|
+import java.io.Closeable;
|
|
|
+import java.io.IOException;
|
|
|
+import java.util.concurrent.atomic.AtomicReference;
|
|
|
+import net.ranides.assira.functional.CheckedSupplier;
|
|
|
+
|
|
|
+/**
|
|
|
+ *
|
|
|
+ * @author Ranides Atterwim <ranides@gmail.com>
|
|
|
+ */
|
|
|
+public final class IOHandle<T extends Closeable> implements Closeable, CheckedSupplier<T, IOException> {
|
|
|
+
|
|
|
+ private final CheckedSupplier<T,IOException> supplier;
|
|
|
+
|
|
|
+ private SharedWrapper<T> ref = null;
|
|
|
+
|
|
|
+ public IOHandle(CheckedSupplier<T,IOException> supplier) {
|
|
|
+ this.supplier = supplier;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void close() throws IOException {
|
|
|
+ SharedWrapper<T> temp = ref;
|
|
|
+ if (temp == null) {
|
|
|
+ synchronized(this) {
|
|
|
+ temp = ref;
|
|
|
+ if (temp != null) {
|
|
|
+ IOUtils.close(ref.value);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public T get() throws IOException {
|
|
|
+ SharedWrapper<T> temp = ref;
|
|
|
+ if (temp == null) {
|
|
|
+ synchronized(this) {
|
|
|
+ temp = ref;
|
|
|
+ if (temp == null) {
|
|
|
+ ref = temp = new SharedWrapper<>(supplier.get());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return temp.value;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static final class SharedWrapper<T> {
|
|
|
+
|
|
|
+ public final T value;
|
|
|
+
|
|
|
+ public SharedWrapper(T value) {
|
|
|
+ this.value = value;
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+}
|