'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?
Solution 1:[1]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | matt |