/******************************************************************************* * Copyright (c) 2007, 2010 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.utils.datastructures; import java.util.concurrent.ConcurrentHashMap; import org.simantics.utils.datastructures.disposable.AbstractDisposable; /** * This class provides context-local variables. There is a different value for * each context. This class handles disposing of all values if optional * disposer is provided. * * @param */ public class ContextLocal extends AbstractDisposable { protected ConcurrentHashMap reg = new ConcurrentHashMap(); public static interface Disposer { public void dispose(T object); } Disposer disposer; /** * Creates context-local variable container. */ public ContextLocal() { } /** * Create context-local variable container. * Container created with this method takes ownership of its object. * * @param disposed */ public ContextLocal(Disposer disposer) { this.disposer = disposer; } /** * Gets the object associated in the specified context * * @param context * @return associated Object or null if not found */ public T get(Object context) { return reg.get(context); } /** * Associates the specified Object with the specified context. * * @param context * @param monitor */ public void replace(Object context, T value) { T old = value != null ? reg.put(context, value) : reg.remove(context); if (old!=null && disposer!=null) disposer.dispose(old); } public void remove(Object context) { replace(context, null); } @Override protected void doDispose() { if (disposer!=null) for (T lr : reg.values()) { disposer.dispose(lr); } reg.clear(); } }