1 /*******************************************************************************
\r
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
\r
3 * in Industry THTH ry.
\r
4 * All rights reserved. This program and the accompanying materials
\r
5 * are made available under the terms of the Eclipse Public License v1.0
\r
6 * which accompanies this distribution, and is available at
\r
7 * http://www.eclipse.org/legal/epl-v10.html
\r
10 * VTT Technical Research Centre of Finland - initial API and implementation
\r
11 *******************************************************************************/
\r
12 package org.simantics.db.common.procedure.single.wrapper;
\r
14 import java.util.concurrent.atomic.AtomicBoolean;
\r
15 import java.util.concurrent.atomic.AtomicInteger;
\r
17 import org.simantics.db.AsyncReadGraph;
\r
18 import org.simantics.db.common.utils.Logger;
\r
19 import org.simantics.db.exception.NoSingleResultException;
\r
20 import org.simantics.db.procedure.AsyncProcedure;
\r
22 final public class DeepSingleOrErrorProcedure<Result> {
\r
24 private Result result = null;
\r
25 final AsyncProcedure<Result> procedure;
\r
26 final AtomicBoolean done = new AtomicBoolean(false);
\r
27 final AtomicBoolean found = new AtomicBoolean(false);
\r
28 final AtomicInteger ready = new AtomicInteger(1);
\r
30 public DeepSingleOrErrorProcedure(AsyncProcedure<Result> procedure) {
\r
32 this.procedure = procedure;
\r
38 ready.incrementAndGet();
\r
42 public void dec(AsyncReadGraph graph) {
\r
44 if(ready.decrementAndGet() == 0) {
\r
45 // Shall fire exactly once!
\r
46 if(done.compareAndSet(false, true)) {
\r
48 if(found.compareAndSet(false, true)) {
\r
49 procedure.exception(graph, new NoSingleResultException("No results."));
\r
51 procedure.execute(graph, result);
\r
53 } catch (Throwable t) {
\r
54 Logger.defaultLogError(t);
\r
61 public void offer(AsyncReadGraph graph, Result result) {
\r
63 if(found.compareAndSet(false, true)) {
\r
64 this.result = result;
\r
66 // Shall fire exactly once!
\r
67 if(done.compareAndSet(false, true)) {
\r
69 procedure.exception(graph, new NoSingleResultException(this.result + " and " + result));
\r
70 } catch (Throwable t) {
\r
71 Logger.defaultLogError(t);
\r
78 public void exception(AsyncReadGraph graph, Throwable t) {
\r
79 // Shall fire exactly once!
\r
80 if(done.compareAndSet(false, true)) {
\r
82 procedure.exception(graph, t);
\r
83 } catch (Throwable t2) {
\r
84 Logger.defaultLogError(t2);
\r