Java cant edit thread stopwatch timeout


Hey I created this code for timeout in my tcp communication, but after I run thread, I can’t change the end time? any ideas?

public class Timer extends Thread{
    ThreadLocal<Long> endTime= new ThreadLocal<>() {
        public Long initialValue() {
            return System.currentTimeMillis()+1000;

    private Client client;

    public void resetTimer(){

    Timer(Client client){

    public void run() {
        while (true) {
            if (endTime.get()<System.currentTimeMillis()) {

Well I can, but in the actual if the value stays initial?

>Solution :

Using ThreadLocal<Long> endTime completely defeats the purpose of your value. Each thread has it’s own value. So your start your "Timer" in that run loop there is endTime.get() which returns the value for your timer thread.

If from another thread you call endTime.set(...) it will set the value for the other thread that you call the method from. Not your Timer thread.

Maybe you want an AtomicLong;

Leave a ReplyCancel reply