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); } } } } }