Ranides Atterwim пре 9 година
родитељ
комит
39ccfaf717
1 измењених фајлова са 66 додато и 0 уклоњено
  1. 66 0
      assira/src/main/java/net/ranides/assira/io/IOHandle.java

+ 66 - 0
assira/src/main/java/net/ranides/assira/io/IOHandle.java

@@ -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;
+		}
+		
+	}
+    
+    
+}