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