I have a multithreaded Java application that makes uses ThreadLocal fields to keep the threads isolated from each other. As part of this application I also have a requirement to implement timeouts on certain functions to prevent DOS attacks.
I’m looking for a way to time out a Java function that is running in the current thread
I’ve seen plenty of solutions such as How to timeout a thread which will create a Future to execute some code, launch it in a new thread and and wait for it to complete. I want to make it work the other way round.
Consider the following multi-threaded code:
class MyClass {
ThreadLocal<AtomicInteger> counter = ThreadLocal.withInitial(AtomicInteger::new);
public void entry() throws Exception {
I_need_a_timeout(100);
int result = counter.get().get(); // If there is no time out this will be 100
}
private void I_need_a_timeout(int loop) throws Exception {
while (loop-- >= 0) {
counter.get().incrementAndGet();
Thread.sleep(100); // Do some work
}
}
}
I need to be able to terminate I_need_a_timeout
if it runs for too long, but if I were to execute it in a future then it would have it’s own thread and therefore it’s own counter so the value read by the calling code would always be 0