Home > database >  Java cant edit thread stopwatch timeout
Java cant edit thread stopwatch timeout

Time:05-14

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<>() {
        @Override
        public Long initialValue() {
            return System.currentTimeMillis() 1000;
        }
    };

    private Client client;

    public void resetTimer(){
        endTime.set((System.currentTimeMillis()) 1000);
    }

    Timer(Client client){
        this.client=client;
        endTime.set(System.currentTimeMillis() 1000);
    }

    public void run() {
        while (true) {
            if (endTime.get()<System.currentTimeMillis()) {
                client.endTimeout();
                return;
            }
        }
    }
}

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

CodePudding user response:

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;

  • Related