'The service variable is not read in a method running in another thread

The Spring application In the service spins an endless cycle

@Service
public class MyService {
    public boolean isStart = false;

    @Async("threadPoolTaskExecutor")
    public void sending() {        
        while (isStartService) {
        ...
        }     
    }
}

@Service
public class OneService {
  @Autowired  
  private final MyService myService;
  
  public void start(boolean isStautus) {
    myService.isStart = true;
    myService.sending();
 }
}

In another service, I set the value of the variable is Start Service = true. While there was no Async annotation on this method, everything worked. But as soon as it was added, and it began to run in a separate thread, the isStartService variable inside this method is now always = false. The loop is never executed. How do I correctly pass the value of this variable inside this stream. I.e. at first it should be true, and after some time its value is passed false and thus the method stops working.

I tried to make the isStart variable as volatile. It didn't help



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source