]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.db.common/src/org/simantics/db/common/procedure/BlockingAsyncProcedure.java
Work in progress
[simantics/platform.git] / bundles / org.simantics.db.common / src / org / simantics / db / common / procedure / BlockingAsyncProcedure.java
index d239c87f709aeaa47055fcc57fdd6196a5310736..da3ec4af81a95885ff06727bae7b964fdc515c97 100644 (file)
@@ -25,12 +25,14 @@ public class BlockingAsyncProcedure<Result> implements AsyncProcedure<Result> {
        final private Object key;
     private Result result = null;
     private Throwable exception = null;
+    final private AsyncReadGraph graph;
     final private AsyncProcedure<Result> procedure;
     final private Semaphore semaphore = new Semaphore(0);
 //    final private AtomicBoolean latch;
     
-    public BlockingAsyncProcedure(AsyncProcedure<Result> procedure, Object key) {
+    public BlockingAsyncProcedure(AsyncReadGraph graph, AsyncProcedure<Result> procedure, Object key) {
 //     assert(procedure != null);
+       this.graph = graph;
        this.key = key;
         this.procedure = procedure;
         if(key == null)
@@ -74,14 +76,34 @@ public class BlockingAsyncProcedure<Result> implements AsyncProcedure<Result> {
         
     }
     
-    public Result get() throws DatabaseException {
+    private void waitFor() throws DatabaseException {
+
+       boolean success = false;
+       success = semaphore.tryAcquire();
+       if(success) return;
+       
+       while(!success) {
+               
+               if(graph.performPending()) {
+                       // Some task was done
+                       success = semaphore.tryAcquire();               
+               } else {
+                       // Nothing to do - just wait
+               try {
+                               success = semaphore.tryAcquire(10, TimeUnit.SECONDS);
+                               if(!success) throw new DatabaseException("Timeout while waiting for async request to complete: " + key);
+                       } catch (InterruptedException e) {
+                               throw new DatabaseException(e);
+                       }
+               }
+                               
+       }
        
-       try {
-                       boolean success = semaphore.tryAcquire(10, TimeUnit.SECONDS);
-                       if(!success) throw new DatabaseException("Timeout while waiting for async request to complete: " + key);
-               } catch (InterruptedException e) {
-                       throw new DatabaseException(e);
-               }
+    }
+    
+    public Result get() throws DatabaseException {
+
+       waitFor();
        
        if(exception != null) {
                if(exception instanceof DatabaseException) throw (DatabaseException)exception;