Friday, January 16, 2009

ThreadLocal

The ThreadLocal class behaves much like the various Reference classes in java.lang.ref; it acts as an indirect handle for storing or retrieving a value. Listing 1 shows the ThreadLocal interface.


public class ThreadLocal {
public Object get();
public void set(Object newValue);
public Object initialValue();
}

See: Exploiting ThreadLocal to enhance scalability


public class EntityChangeTracker {

private static ThreadLocal<List<EntityChange>> entityChangeThreadLocal = new ThreadLocal<List<EntityChange>>() {
protected List<EntityChange> initialValue() {
return new ArrayList<EntityChange>();
}
};

public static List<EntityChange> getEntityChanges() {
return entityChangeThreadLocal.get();
}

public static void addEntityChange(Entity<?> e, AuditOperation opr) {
List<EntityChange> list = entityChangeThreadLocal.get();
list.add(new EntityChange(e, opr));
}

public static void clear() {
entityChangeThreadLocal.get().clear();
}
}

No comments: