+/*******************************************************************************\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.utils.datastructures;\r
+\r
+import java.util.concurrent.ConcurrentHashMap;\r
+\r
+import org.simantics.utils.datastructures.disposable.AbstractDisposable;\r
+\r
+/**\r
+ * This class provides context-local variables. There is a different value for \r
+ * each context. This class handles disposing of all values if optional\r
+ * disposer is provided. \r
+ *\r
+ * @param <T>\r
+ */\r
+public class ContextLocal<T> extends AbstractDisposable {\r
+ \r
+ protected ConcurrentHashMap<Object, T> reg = new ConcurrentHashMap<Object, T>();\r
+ \r
+ public static interface Disposer<T> {\r
+ public void dispose(T object);\r
+ }\r
+ \r
+ Disposer<T> disposer;\r
+ \r
+ /**\r
+ * Creates context-local variable container.\r
+ */\r
+ public ContextLocal() \r
+ { \r
+ }\r
+ \r
+ /**\r
+ * Create context-local variable container.\r
+ * Container created with this method takes ownership of its object.\r
+ * \r
+ * @param disposed\r
+ */\r
+ public ContextLocal(Disposer<T> disposer)\r
+ {\r
+ this.disposer = disposer;\r
+ }\r
+ \r
+ /**\r
+ * Gets the object associated in the specified context\r
+ * \r
+ * @param context\r
+ * @return associated Object or <code>null</code> if not found\r
+ */\r
+ public T get(Object context) {\r
+ return reg.get(context);\r
+ }\r
+\r
+ /**\r
+ * Associates the specified Object with the specified context.\r
+ * \r
+ * @param context\r
+ * @param monitor\r
+ */\r
+ public void replace(Object context, T value) {\r
+ T old = value != null ? reg.put(context, value) : reg.remove(context);\r
+ if (old!=null && disposer!=null)\r
+ disposer.dispose(old);\r
+ }\r
+ \r
+ public void remove(Object context) {\r
+ replace(context, null);\r
+ }\r
+\r
+ @Override\r
+ protected void doDispose() {\r
+ if (disposer!=null)\r
+ for (T lr : reg.values()) {\r
+ disposer.dispose(lr);\r
+ }\r
+ reg.clear();\r
+ }\r
+\r
+\r
+}\r
+\r