I have situation where I need to increment a Thread local variable every 1 second for the thread that is currently executing. For example consider following code snippet
public class DemoApplication {
public static final ThreadLocal<Integer> threadTest =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return 1;
}
};
public static void main(String[]args) {
Timer timer = new Timer();
timer.schedule(new timerTask(), 0, 1000);
DummyApplication2 DM2 = new DummyApplication2();
DM2.start();
while(true) {
try{
System.out.println("main thread test value" + threadTest.get());
Thread.sleep(2000);
}
}catch (InterruptedException e) {
System.out.println("Thread interrupted in main");
}
}
}
}
class timerTask extends TimerTask{
private int i= 0;
public void run() {
DemoApplication.threadTest.set(i);
i+=1;
}
}
class DummyApplication2 extends Thread{
public void run() {
while (true) {
try {
Thread.sleep(1000);
System.out.println("Second thread test value " + DemoApplication.threadTest.get());
} catch(InterruptedException e){
System.out.println("Got interrupted exception");
}
}
}
}
The above code create two threads and also creates a timer that executes a scheduled task every 1 second.
However for the situation above since timerTask is getting executed on a separate thread it does not increment the thread local counter threadTest for other two threads that are still running. One way to fix this is by iterating over the list of available running threads, however I am not sure how efficient that would be if number of threads keep increasing (Also the result would not be correct coz e.g in the above code DemoApplication2 class thread local variable should increment twice as fast as main thread since it sleeps for only a half a time compared to main).
So I was wondering whether there is any way to create a timer that can run in a currently executing thread rather than in its own thread.
Any help on this would be great, Thanks
classwith a capital letter!!