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.single.wrapper;
14 import java.util.concurrent.atomic.AtomicBoolean;
15 import java.util.concurrent.atomic.AtomicInteger;
17 import org.simantics.db.AsyncReadGraph;
18 import org.simantics.db.common.utils.Logger;
19 import org.simantics.db.exception.NoSingleResultException;
20 import org.simantics.db.procedure.AsyncProcedure;
22 final public class DeepSingleOrErrorProcedure<Result> {
24 private Result result = null;
25 final AsyncProcedure<Result> procedure;
26 final AtomicBoolean done = new AtomicBoolean(false);
27 final AtomicBoolean found = new AtomicBoolean(false);
28 final AtomicInteger ready = new AtomicInteger(1);
30 public DeepSingleOrErrorProcedure(AsyncProcedure<Result> procedure) {
32 this.procedure = procedure;
38 ready.incrementAndGet();
42 public void dec(AsyncReadGraph graph) {
44 if(ready.decrementAndGet() == 0) {
45 // Shall fire exactly once!
46 if(done.compareAndSet(false, true)) {
48 if(found.compareAndSet(false, true)) {
49 procedure.exception(graph, new NoSingleResultException("No results."));
51 procedure.execute(graph, result);
53 } catch (Throwable t) {
54 Logger.defaultLogError(t);
61 public void offer(AsyncReadGraph graph, Result result) {
63 if(found.compareAndSet(false, true)) {
66 // Shall fire exactly once!
67 if(done.compareAndSet(false, true)) {
69 procedure.exception(graph, new NoSingleResultException(this.result + " and " + result));
70 } catch (Throwable t) {
71 Logger.defaultLogError(t);
78 public void exception(AsyncReadGraph graph, Throwable t) {
79 // Shall fire exactly once!
80 if(done.compareAndSet(false, true)) {
82 procedure.exception(graph, t);
83 } catch (Throwable t2) {
84 Logger.defaultLogError(t2);