]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.db.common/src/org/simantics/db/common/GraphSemaphore.java
Work in progress
[simantics/platform.git] / bundles / org.simantics.db.common / src / org / simantics / db / common / GraphSemaphore.java
diff --git a/bundles/org.simantics.db.common/src/org/simantics/db/common/GraphSemaphore.java b/bundles/org.simantics.db.common/src/org/simantics/db/common/GraphSemaphore.java
new file mode 100644 (file)
index 0000000..2924f02
--- /dev/null
@@ -0,0 +1,48 @@
+package org.simantics.db.common;
+
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+
+import org.simantics.db.AsyncReadGraph;
+import org.simantics.db.exception.DatabaseException;
+
+public class GraphSemaphore extends Semaphore {
+
+       private static final long serialVersionUID = 2114861433176831938L;
+       
+       private final AsyncReadGraph graph;
+       
+       public GraphSemaphore(AsyncReadGraph graph, int permits) {
+               super(permits);
+               this.graph = graph;
+       }
+
+       public void waitFor(int permits) throws DatabaseException, InterruptedException {
+               
+       boolean success = false;
+       success = tryAcquire(permits);
+       if(success) return;
+       
+       while(!success) {
+               
+               if(graph.performPending()) {
+                       // Some task was done
+                       success = tryAcquire(permits);          
+               } else {
+                       // Nothing to do - just wait
+               try {
+                               success = tryAcquire(permits, 10, TimeUnit.SECONDS);
+                               if(!success) throw new DatabaseException("Timeout while waiting for async request to complete.");
+                       } catch (InterruptedException e) {
+                               throw new DatabaseException(e);
+                       }
+               }
+                               
+       }
+
+               
+       }
+       
+       
+
+}