--- /dev/null
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
+ * in Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ * VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.db.common.procedure.guarded;\r
+\r
+import java.util.concurrent.atomic.AtomicBoolean;\r
+import java.util.concurrent.atomic.AtomicInteger;\r
+\r
+import org.simantics.db.AsyncReadGraph;\r
+import org.simantics.db.common.procedure.adapter.AsyncProcedureSupport;\r
+import org.simantics.db.procedure.AsyncMultiProcedure;\r
+\r
+abstract public class GuardedAsyncMultiProcedure<T> implements AsyncMultiProcedure<T>, AsyncProcedureSupport {\r
+\r
+ private final AsyncMultiProcedure<T> procedure;\r
+ private final AtomicBoolean onceGuard = new AtomicBoolean(false);\r
+ private final AtomicInteger resultCounter;\r
+\r
+ public GuardedAsyncMultiProcedure(AsyncMultiProcedure<T> procedure) {\r
+ this.procedure = procedure;\r
+ this.resultCounter = new AtomicInteger(1);\r
+ }\r
+\r
+ @Override\r
+ final public void exception(AsyncReadGraph graph, Throwable t) {\r
+ except(graph, t);\r
+ }\r
+\r
+ protected void except(AsyncReadGraph graph, Throwable t) {\r
+ if (onceGuard.compareAndSet(false, true)) {\r
+ procedure.exception(graph, t);\r
+ }\r
+ }\r
+\r
+ protected void offer(AsyncReadGraph graph, T item) {\r
+ if (!onceGuard.get()) {\r
+ procedure.execute(graph, item);\r
+ }\r
+ }\r
+\r
+ protected void dec(AsyncReadGraph graph) {\r
+ if (resultCounter.decrementAndGet() <= 0) {\r
+ if (onceGuard.compareAndSet(false, true)) {\r
+ procedure.finished(graph);\r
+ }\r
+ }\r
+ }\r
+ \r
+ protected void inc() {\r
+ resultCounter.incrementAndGet();\r
+ }\r
+\r
+ @Override\r
+ final public void finished(AsyncReadGraph graph) {\r
+ dec(graph);\r
+ }\r
+\r
+}\r