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 NullSingleOrExceptionProcedure<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 NullSingleOrExceptionProcedure(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 procedure.execute(graph, result);
49 } catch (Throwable t) {
50 Logger.defaultLogError(t);
57 public void offer(AsyncReadGraph graph, Result result) {
59 if(found.compareAndSet(false, true)) {
62 // Shall fire exactly once!
63 if(done.compareAndSet(false, true)) {
65 procedure.exception(graph, new NoSingleResultException(procedure.toString(), -1));
66 } catch (Throwable t) {
67 Logger.defaultLogError(t);
74 public void exception(AsyncReadGraph graph, Throwable t) {
75 // Shall fire exactly once!
76 if(done.compareAndSet(false, true)) {
78 procedure.exception(graph, t);
79 } catch (Throwable t2) {
80 Logger.defaultLogError(t2);