Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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<>() {
        @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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading