Skip to content

Instantly share code, notes, and snippets.

@karanmalhi
Created July 28, 2011 19:37
Show Gist options
  • Save karanmalhi/1112356 to your computer and use it in GitHub Desktop.
Save karanmalhi/1112356 to your computer and use it in GitHub Desktop.
ThreadLocal example
import java.util.ArrayList;
import java.util.List;
public class Debugger {
public static void main(String[] args) {
ThreadGroup cleanupThreads = new ThreadGroup("Cleanup group");
Thread t1 = new Thread(cleanupThreads, new Printer());
Thread t2 = new Thread(cleanupThreads, new Printer());
t1.start();
t2.start();
}
private static class DebugLocal extends ThreadLocal<List<String>> {
@Override
protected List<String> initialValue() {
return new ArrayList<String>();
}
List<String> getList() {
return super.get();
}
}
private static final DebugLocal local = new DebugLocal();
public void put(String message) {
local.getList().add(message);
}
public List<String> getMessages() {
return local.getList();
}
}
class Printer implements Runnable {
@Override
public void run() {
new Foo().foo();
new Bar().bar();
System.out.println(new Debugger().getMessages());
}
}
class Foo {
void foo() {
Debugger d = new Debugger();
d.put("Some message here by foo");
}
}
class Bar {
void bar() {
Debugger d = new Debugger();
d.put("Some message here by bar");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment