]> gerrit.simantics Code Review - simantics/platform.git/blob - procedure/guarded/GuardedAsyncProcedureWrapper.java
Fixed multiple issues causing dangling references to discarded queries
[simantics/platform.git] / procedure / guarded / GuardedAsyncProcedureWrapper.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.common.procedure.guarded;
13
14 import java.util.concurrent.atomic.AtomicBoolean;
15 import java.util.concurrent.atomic.AtomicInteger;
16
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;
21
22 /**
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>.
28  * 
29  * @author Tuukka Lehtonen
30  * 
31  * @param <T>
32  */
33 public class GuardedAsyncProcedureWrapper<T> extends AsyncProcedureAdapter<T> {
34
35     private final AsyncProcedure<T> procedure;
36     private final AtomicBoolean     onceGuard = new AtomicBoolean(false);
37     private final AtomicInteger     resultCounter;
38
39     public GuardedAsyncProcedureWrapper(AsyncProcedure<T> procedure, int expectedResults) {
40         this.procedure = procedure;
41         this.resultCounter = new AtomicInteger(expectedResults);
42     }
43
44     @Override
45     public void exception(AsyncReadGraph graph, Throwable t) {
46         if (onceGuard.compareAndSet(false, true)) {
47             procedure.exception(graph, t);
48         }
49     }
50
51     @Override
52     public void execute(AsyncReadGraph graph, T result) {
53         int count = resultCounter.decrementAndGet();
54         if (count == 0) {
55             if (onceGuard.compareAndSet(false, true)) {
56                 procedure.execute(graph, result);
57             }
58         } else if (count < 0) {
59             System.out.println(this + ": execute invoked more than expected (count=" + count + ", procedure=" + procedure + ")");
60         }
61     }
62
63 }