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.guarded;
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.procedure.adapter.AsyncProcedureSupport;
19 import org.simantics.db.procedure.AsyncMultiProcedure;
21 abstract public class GuardedAsyncMultiProcedure<T> implements AsyncMultiProcedure<T>, AsyncProcedureSupport {
23 private final AsyncMultiProcedure<T> procedure;
24 private final AtomicBoolean onceGuard = new AtomicBoolean(false);
25 private final AtomicInteger resultCounter;
27 public GuardedAsyncMultiProcedure(AsyncMultiProcedure<T> procedure) {
28 this.procedure = procedure;
29 this.resultCounter = new AtomicInteger(1);
33 final public void exception(AsyncReadGraph graph, Throwable t) {
37 protected void except(AsyncReadGraph graph, Throwable t) {
38 if (onceGuard.compareAndSet(false, true)) {
39 procedure.exception(graph, t);
43 protected void offer(AsyncReadGraph graph, T item) {
44 if (!onceGuard.get()) {
45 procedure.execute(graph, item);
49 protected void dec(AsyncReadGraph graph) {
50 if (resultCounter.decrementAndGet() <= 0) {
51 if (onceGuard.compareAndSet(false, true)) {
52 procedure.finished(graph);
57 protected void inc() {
58 resultCounter.incrementAndGet();
62 final public void finished(AsyncReadGraph graph) {