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