Search code examples
javamultithreadingscheduled-taskscancellation

How do I run a Java thread at an interval and cancel it if it exceeds a time limit?


I'm trying to design a system by which I can have a Thread execute at a certain interval of time (e.g. 10 seconds), and also have it cancelled at a certain time if it overruns a time limit (e.g. 5 seconds). Maybe this isn't the right way to do what i'm looking for but id like some help nonetheless.

I thought about using the ExectuorService to perform this, but will I run into problems with it?


Solution

  • ScheduledExecutorService

    have a Thread execute at a certain interval of time (e.g. 10 seconds)

    You can.

    Use a ScheduledExecutorService to repeatedly execute a task at a specified period of time.

    This has been covered extensively on Stack Overflow. Search to learn more.

    Forcibly halt a thread

    have it cancelled at a certain time if it overruns a time limit (e.g. 5 seconds).

    You cannot.

    Java provides no way to forcibly halt the execution of a thread.

    Java concurrency allows only for cooperative cancellation. You can signal your intention for another thread to halt by “interrupting”. But this interrupt attempt merely sets a flag, and wakes the thread if sleeping. The task must be coded to regularly look for the interrupt flag. If flag is set, the task must be coded to then 👉 end its own execution.

    This too has been covered extensively on Stack Overflow. Search to learn more.