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.AsyncProcedureAdapter;
19 import org.simantics.db.procedure.AsyncProcedure;
20 import org.simantics.db.procedure.Procedure;
23 * An asynchronous database callback procedure that is guarded against multiple
24 * invocations to {@link Procedure#execute(Object)} and
25 * {@link Procedure#exception(Throwable)}. Only the first invocation of is
26 * delegated or the Nth invocation to {@link Procedure#execute(Object)} where
27 * Nth is <code>expectedResults</code>.
29 * @author Tuukka Lehtonen
33 public class GuardedAsyncProcedureWrapper<T> extends AsyncProcedureAdapter<T> {
35 private final AsyncProcedure<T> procedure;
36 private final AtomicBoolean onceGuard = new AtomicBoolean(false);
37 private final AtomicInteger resultCounter;
39 public GuardedAsyncProcedureWrapper(AsyncProcedure<T> procedure, int expectedResults) {
40 this.procedure = procedure;
41 this.resultCounter = new AtomicInteger(expectedResults);
45 public void exception(AsyncReadGraph graph, Throwable t) {
46 if (onceGuard.compareAndSet(false, true)) {
47 procedure.exception(graph, t);
52 public void execute(AsyncReadGraph graph, T result) {
53 int count = resultCounter.decrementAndGet();
55 if (onceGuard.compareAndSet(false, true)) {
56 procedure.execute(graph, result);
58 } else if (count < 0) {
59 System.out.println(this + ": execute invoked more than expected (count=" + count + ", procedure=" + procedure + ")");