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
10 * VTT Technical Research Centre of Finland - initial API and implementation
\r
11 *******************************************************************************/
\r
12 package org.simantics.utils.datastructures;
\r
14 import java.util.concurrent.ConcurrentHashMap;
\r
16 import org.simantics.utils.datastructures.disposable.AbstractDisposable;
\r
19 * This class provides context-local variables. There is a different value for
\r
20 * each context. This class handles disposing of all values if optional
\r
21 * disposer is provided.
\r
25 public class ContextLocal<T> extends AbstractDisposable {
\r
27 protected ConcurrentHashMap<Object, T> reg = new ConcurrentHashMap<Object, T>();
\r
29 public static interface Disposer<T> {
\r
30 public void dispose(T object);
\r
33 Disposer<T> disposer;
\r
36 * Creates context-local variable container.
\r
38 public ContextLocal()
\r
43 * Create context-local variable container.
\r
44 * Container created with this method takes ownership of its object.
\r
48 public ContextLocal(Disposer<T> disposer)
\r
50 this.disposer = disposer;
\r
54 * Gets the object associated in the specified context
\r
57 * @return associated Object or <code>null</code> if not found
\r
59 public T get(Object context) {
\r
60 return reg.get(context);
\r
64 * Associates the specified Object with the specified context.
\r
69 public void replace(Object context, T value) {
\r
70 T old = value != null ? reg.put(context, value) : reg.remove(context);
\r
71 if (old!=null && disposer!=null)
\r
72 disposer.dispose(old);
\r
75 public void remove(Object context) {
\r
76 replace(context, null);
\r
80 protected void doDispose() {
\r
82 for (T lr : reg.values()) {
\r
83 disposer.dispose(lr);
\r