]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.common/src/org/simantics/db/common/procedure/guarded/GuardedAsyncMultiProcedure.java
Add logging by default to adapters exception-methods
[simantics/platform.git] / bundles / org.simantics.db.common / src / org / simantics / db / common / procedure / guarded / GuardedAsyncMultiProcedure.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.AsyncProcedureSupport;
19 import org.simantics.db.procedure.AsyncMultiProcedure;
20
21 abstract public class GuardedAsyncMultiProcedure<T> implements AsyncMultiProcedure<T>, AsyncProcedureSupport {
22
23     private final AsyncMultiProcedure<T> procedure;
24     private final AtomicBoolean     onceGuard = new AtomicBoolean(false);
25     private final AtomicInteger     resultCounter;
26
27     public GuardedAsyncMultiProcedure(AsyncMultiProcedure<T> procedure) {
28         this.procedure = procedure;
29         this.resultCounter = new AtomicInteger(1);
30     }
31
32     @Override
33     final public void exception(AsyncReadGraph graph, Throwable t) {
34         except(graph, t);
35     }
36
37     protected void except(AsyncReadGraph graph, Throwable t) {
38         if (onceGuard.compareAndSet(false, true)) {
39             procedure.exception(graph, t);
40         }
41     }
42
43     protected void offer(AsyncReadGraph graph, T item) {
44         if (!onceGuard.get()) {
45                 procedure.execute(graph, item);
46         }
47     }
48
49     protected void dec(AsyncReadGraph graph) {
50         if (resultCounter.decrementAndGet() <= 0) {
51             if (onceGuard.compareAndSet(false, true)) {
52                 procedure.finished(graph);
53             }
54         }
55     }
56     
57     protected void inc() {
58         resultCounter.incrementAndGet();
59     }
60
61         @Override
62         final public void finished(AsyncReadGraph graph) {
63                 dec(graph);
64         }
65
66 }