Search code examples
javamultithreadingstm

Stop a Runnable in a Thread imediatly


I try to implement a version of software transactional memory library in java with some sort of scheduler which holds some Thread objects. I want to implement a mechanism where the scheduler tells the Thread to immediatly stop execution, drop its Runnable, create a new one and rerun it. This is really half cooked so far but what I don't want is to recreate the hole Thread because it will work as a state holder for several Variables (deepcopies of other variables only the Thread has - copy tasks are a choke here so the Thread should not be fully recreated)

My problem is that I don't know about anything that terminates a method while it executes and frees all the resources (If the scheduler tells the thread to restart everything the Runnable did is invalid and must be redone) and start the run method again with fresh input variables.

The goal is to avoid unecesarry executions and there should be no variable in the runnable which asks if it was interreupted to then skip the execution or something. Just stop the execution and kill it from something the runnable itself is not aware off. I hope it's clear what I want if not please ask for the unclear points help would be very appreciated :)


Solution

  • A simple Tutorial to cancel the Runnable and start it again.

    public class RestartThreadTutorial {
    public static void main(String args[]){
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        Future<?> taskHandler = executorService.submit(new Task());
        //restart the task after 3 seconds.
        try{
            Thread.sleep(3000);
        }catch(InterruptedException e){
            //empty
        }
        taskHandler.cancel(true); //it will cancel the running thread
        if (taskHandler.isCancelled()==true){//check the thread is cancelled
            executorService.submit(new Task());//then create new thread..
        }
    }
    
    public static class Task implements Runnable{
        private int secondsCounter;
        @Override
        public void run(){
            while(true){
                System.out.println("Thread -"+Thread.currentThread().getName()+"elapsed - "+ (secondsCounter++) +"second");
                try{
                    Thread.sleep(1000);
                }catch(InterruptedException e){
                    e.printStackTrace();
                    break;
                }
            }
        }
    }
    }