]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.common/src/org/simantics/db/common/procedure/guarded/GuardedAsyncMultiProcedure.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.db.common / src / org / simantics / db / common / procedure / guarded / GuardedAsyncMultiProcedure.java
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
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.db.common.procedure.guarded;\r
13 \r
14 import java.util.concurrent.atomic.AtomicBoolean;\r
15 import java.util.concurrent.atomic.AtomicInteger;\r
16 \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
20 \r
21 abstract public class GuardedAsyncMultiProcedure<T> implements AsyncMultiProcedure<T>, AsyncProcedureSupport {\r
22 \r
23     private final AsyncMultiProcedure<T> procedure;\r
24     private final AtomicBoolean     onceGuard = new AtomicBoolean(false);\r
25     private final AtomicInteger     resultCounter;\r
26 \r
27     public GuardedAsyncMultiProcedure(AsyncMultiProcedure<T> procedure) {\r
28         this.procedure = procedure;\r
29         this.resultCounter = new AtomicInteger(1);\r
30     }\r
31 \r
32     @Override\r
33     final public void exception(AsyncReadGraph graph, Throwable t) {\r
34         except(graph, t);\r
35     }\r
36 \r
37     protected void except(AsyncReadGraph graph, Throwable t) {\r
38         if (onceGuard.compareAndSet(false, true)) {\r
39             procedure.exception(graph, t);\r
40         }\r
41     }\r
42 \r
43     protected void offer(AsyncReadGraph graph, T item) {\r
44         if (!onceGuard.get()) {\r
45                 procedure.execute(graph, item);\r
46         }\r
47     }\r
48 \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
53             }\r
54         }\r
55     }\r
56     \r
57     protected void inc() {\r
58         resultCounter.incrementAndGet();\r
59     }\r
60 \r
61         @Override\r
62         final public void finished(AsyncReadGraph graph) {\r
63                 dec(graph);\r
64         }\r
65 \r
66 }\r