To terminate a peviously running function and start a new one in Springboot

Viewed 20

I have one HTML page. There are two buttons "Start" and "Stop". Start button makes a HTTP request to my controller and a function starts. This function runs infinitely. I want that when I press Stop button the previous function should stop.

My controller looks like this.

package com.springbootLogging.demo;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping(path="/")
    public class appController{
        
        Logger logger = LoggerFactory.getLogger(appController.class);
        
        
       @CrossOrigin
        @GetMapping(path="/startLog")
        public void startPrintingLogs() {
            
            while(true) {
                logger.debug("It is a debug logger.");
                logger.error("It is an error logger.");
                logger.info("It is a info logger.");
                logger.trace("It is a trace logger.");
                logger.warn("It is a warn logger.");
                
            }
    
            
                }
       @CrossOrigin
       @GetMapping(path="/stopLog")
       
       public void StopPrintingLogs() {
           //to do something that it stops the above function
       }
       
      
    }
1 Answers

The best way to do this would be to create a background thread that you keep a reference to and ideally some kind of unique id.

When stop is called with that id you can interrupt the thread.

private static volatile Map<String, Thread> threadlookup = new ConcurrentHashMap<>();

public void start() {
    UUID uuid = UUID.randomUUID();
    Thread thread = new Thread(() -> {
       // never ending task in here
    });
    thread.start();
    threadlookup.put(uuid.toString(), thread);

    // return UUID in http response
}

public void stop(String uuid) {
    Thread thread = threadlookup.get(uuid);
    if (thread == null) {
        //return 404
    } else {
        thread.interrupt();
    }
}

If you only ever want a single thread you can just keep a single reference.

Related