0

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

5
  • why not combine the increment and timer into one thread? Commented Feb 26, 2018 at 2:00
  • 1
    Please start the name of class with a capital letter!! Commented Feb 26, 2018 at 2:00
  • If it's thread local, why does it matter if it's updated. Before you need it. Check the clock, how many 1 seconds have passed in that time. Pretend the variable says that. Commented Feb 26, 2018 at 2:01
  • @AngelKoh I am not sure I understood, can you please elaborate or give an example Commented Feb 26, 2018 at 2:12
  • @BahramdunAdil indeed Commented Feb 26, 2018 at 2:36

2 Answers 2

1

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.

No.

But, you could record the start time and then check the current time in that thread to see how much time has elapsed. It's less a timer than a clock. Then when you care about that value, just look at the time and calculate what it should be.

You could also launch the timer thread locally so it has direct access to the variable and can update it directly. So thread 1 launches thread 2 and thread 2 launches thread 3 which updates the value in thread 2. But, generally sleeping threads aren't a great way to time things.

Sign up to request clarification or add additional context in comments.

1 Comment

I see what you mean, I will try to give it a shot
0

One solution will be one daemon thread will run every second and check if the thread is running and update increment number.For this solution you need to manage or created by thread factory with wrapper can give unique name or id to thread and will use as key while daemon thread update the count.For storing you can use a key value data structure like Map.

Optimize to above solution Every thread you create pass a listener class having start and end method.When thread start it will notify the metrics class which will start a meter to increment till stop method call.when thread stops it will call end method.So dynamically you can calculate increment.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.