]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.common/src/org/simantics/db/common/GraphSemaphore.java
2924f0275a394cb57e160a752c8323cb3c84f03d
[simantics/platform.git] / bundles / org.simantics.db.common / src / org / simantics / db / common / GraphSemaphore.java
1 package org.simantics.db.common;
2
3 import java.util.concurrent.Semaphore;
4 import java.util.concurrent.TimeUnit;
5
6 import org.simantics.db.AsyncReadGraph;
7 import org.simantics.db.exception.DatabaseException;
8
9 public class GraphSemaphore extends Semaphore {
10
11         private static final long serialVersionUID = 2114861433176831938L;
12         
13         private final AsyncReadGraph graph;
14         
15         public GraphSemaphore(AsyncReadGraph graph, int permits) {
16                 super(permits);
17                 this.graph = graph;
18         }
19
20         public void waitFor(int permits) throws DatabaseException, InterruptedException {
21                 
22         boolean success = false;
23         success = tryAcquire(permits);
24         if(success) return;
25         
26         while(!success) {
27                 
28                 if(graph.performPending()) {
29                         // Some task was done
30                         success = tryAcquire(permits);          
31                 } else {
32                         // Nothing to do - just wait
33                 try {
34                                 success = tryAcquire(permits, 10, TimeUnit.SECONDS);
35                                 if(!success) throw new DatabaseException("Timeout while waiting for async request to complete.");
36                         } catch (InterruptedException e) {
37                                 throw new DatabaseException(e);
38                         }
39                 }
40                                 
41         }
42
43                 
44         }
45         
46         
47
48 }