Thursday, December 31, 2009

ThreadUtils

Sometimes, we need to save variable to thread, following ThreadUtils is handy to use.

import java.util.HashMap;
import java.util.Map;


public class ThreadUtils {
private static final ThreadLocal sThreadLocalMap = new ThreadLocal();

/**
* Create a ThreadLocal map for storing ThreadLocal variables.
* HashMap is
*/
static {
sThreadLocalMap.set( new HashMap() );
}

/**
* Returns the ThreadLocal variable with the given key.
*
* @param key - unique key of the object.
*
* @return object from given key
*/
public static Object getThreadLocal( final String key )
{
if ( sThreadLocalMap == null || sThreadLocalMap.get() == null ) {
return null;
}


return ((Map)sThreadLocalMap.get()).get( key );
}

/**
* Sets the given object to the Map with the given key.
*
* @param key - unique key of the object
* @param object - object
*/
public static void setThreadLocal( final String key, final Object object )
{
Map map = (Map)sThreadLocalMap.get();

if ( map == null ) {
map = new HashMap();
sThreadLocalMap.set( map );
}

map.put( key, object );
}

/**
* Removes the ThreadLocal variable from the map with the given key.
*
* @param key - key of the variable to remove.
*/
public static void removeThreadLocal( final String key )
{
if ( sThreadLocalMap == null || sThreadLocalMap.get() == null ) {
return;
}

((Map)sThreadLocalMap.get()).remove( key );
}

}

No comments:

Post a Comment