1 /*******************************************************************************
2 * Copyright (c) 2018 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 * Semantum Oy - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.db.impl;
14 import org.simantics.db.AsyncReadGraph;
15 import org.simantics.db.common.utils.Logger;
16 import org.simantics.db.exception.DatabaseException;
17 import org.simantics.db.impl.graph.ReadGraphImpl;
18 import org.simantics.db.procedure.AsyncProcedure;
20 public class BlockingAsyncProcedure<Result> implements AsyncProcedure<Result> {
22 private static final Object NO_RESULT = new Object();
24 private final Object key;
25 private final ReadGraphImpl graph;
26 private final AsyncProcedure<Result> procedure;
28 private Object result = NO_RESULT;
29 private Throwable exception = null;
31 public BlockingAsyncProcedure(ReadGraphImpl graph, AsyncProcedure<Result> procedure, Object key) {
32 this.procedure = procedure;
35 this.graph.asyncBarrier.inc();
39 public void execute(AsyncReadGraph graph, Result result) {
41 this.graph.asyncBarrier.dec();
43 if(procedure != null) procedure.execute(graph, result);
44 } catch (Throwable throwable) {
45 Logger.defaultLogError("AsyncProcedure.execute threw for " + procedure, throwable);
50 public void exception(AsyncReadGraph graph, Throwable t) {
53 if(procedure != null) procedure.exception(graph, t);
54 } catch (Throwable throwable) {
55 Logger.defaultLogError("AsyncProcedure.exception threw for " + procedure, throwable);
57 this.graph.asyncBarrier.dec();
61 public void waitBarrier() {
62 graph.asyncBarrier.waitBarrier(key, graph);
65 @SuppressWarnings("unchecked")
66 public Result get() throws DatabaseException {
68 graph.asyncBarrier.waitBarrier(key, graph);
70 if(exception != null) {
71 if(exception instanceof DatabaseException) throw (DatabaseException)exception;
72 throw new DatabaseException(exception);
74 return (Result)result;
79 public boolean isDone() {
80 return graph.asyncBarrier.get() == 0;
83 @SuppressWarnings("unchecked")
84 public Result getResult() {
85 return (Result)result;
88 public Throwable getException() {
93 public String toString() {
94 return "." + procedure;