1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.db.common.procedure;
14 import java.util.concurrent.Semaphore;
15 import java.util.concurrent.TimeUnit;
16 import java.util.concurrent.atomic.AtomicBoolean;
18 import org.simantics.db.AsyncReadGraph;
19 import org.simantics.db.common.utils.Logger;
20 import org.simantics.db.exception.DatabaseException;
21 import org.simantics.db.procedure.AsyncProcedure;
23 public class BlockingAsyncProcedure<Result> implements AsyncProcedure<Result> {
25 final private Object key;
26 private Result result = null;
27 private Throwable exception = null;
28 final private AsyncProcedure<Result> procedure;
29 final private Semaphore semaphore = new Semaphore(0);
30 // final private AtomicBoolean latch;
32 public BlockingAsyncProcedure(AsyncProcedure<Result> procedure, Object key) {
33 // assert(procedure != null);
35 this.procedure = procedure;
37 System.err.println("asd");
38 //System.err.println("BlockingAsyncProcedure " + key);
39 // latch = new AtomicBoolean(false);
43 public void execute(AsyncReadGraph graph, Result result) {
46 // if(latch.compareAndSet(false, true)) {
48 if(procedure != null) procedure.execute(graph, result);
49 } catch (Throwable throwable) {
50 Logger.defaultLogError("AsyncProcedure.execute threw for " + procedure, throwable);
53 //// System.err.println("ResultCallWrappedSingleQueryProcedure4 dec " + key);
56 // Logger.defaultLogError("Procedure was called many times (this time is execute)");
61 public void exception(AsyncReadGraph graph, Throwable t) {
64 // if(latch.compareAndSet(false, true)) {
66 if(procedure != null) procedure.exception(graph, t);
67 } catch (Throwable throwable) {
68 Logger.defaultLogError("AsyncProcedure.exception threw for " + procedure, throwable);
72 // Logger.defaultLogError("Procedure was called many times (this time is exception)");
77 public Result get() throws DatabaseException {
80 boolean success = semaphore.tryAcquire(10, TimeUnit.SECONDS);
81 if(!success) throw new DatabaseException("Timeout while waiting for async request to complete: " + key);
82 } catch (InterruptedException e) {
83 throw new DatabaseException(e);
86 if(exception != null) {
87 if(exception instanceof DatabaseException) throw (DatabaseException)exception;
88 throw new DatabaseException(exception);
95 public Result getResult() {
99 public Throwable getException() {
104 public String toString() {
105 return "." + procedure;