title: @Async method inside synchronized method Java
body: <p>To summarize the problem, I am trying to call some method which is annotated with @async in a synchronized method. Reason for using @async was because I wish to return the response of the post method (to reduce waiting time on client’s side) and continue doing some post processing work (resetting certain properties). However, as the POST method involve altering a graph database, I declare the method with synchronized keyword to prevent altering of the graph database while another computation is going on. The result of this seem to be that two threads are entering the synchronized method, which shouldn’t be occurring?</p>
  <pre><code>@RestController
  public class Controller {
  
  @PostMapping(path = “/compute”)
  public synchronized String compute() {
  
  System.out.println(“===== &gt; In thread: “ + Thread.currentThread().getName());
  
  System.out.print(“===== &gt; Doing some work in compute”);
  
  ResetService.reset()
  Return(“===== &gt; done computing”)
  }
  
  
  @Service
  public class ResetService {@Async public void reset (){
  
  System.out.println(“===== &gt; resetting in thread: “ + Thread.currentThread().getName());
  #(resetting some properties in neo4j graph database)
  resetMethod();
  System.out.print(“===== &gt; Done Resetting”);
  }
  </code></pre>
  <p>This will give me an output similar to something like this:</p>
  <p>===== &gt; In Thread: http-nio-10080-exec-2</p>
  <p>===== &gt; Doing some work in compute</p>
  <p>===== &gt; done computing</p>
  <p>=====&gt; Resetting in Thread: Async-1</p>
  <p>===== &gt; In Thread: http-nio-10080-exec-3</p>
  <p>===== &gt; Doing some work in compute</p>
  <p>===== &gt; Done Resetting</p>
  <p>My understanding of Synchronized method is that it only allows a single thread to enter the method at any time. But it seems like there are two threads running the Synchronized compute method at the same time. I tried to come up with some reasons for this and the two main ones I could think of are:</p>
  <ol>
  <li><p>Due to different instances of the Controller class, however I recalled reading somewhere that a RESTController is a singleton scope by default, so it shouldn’t be due to this?</p>
  </li>
  <li><p>Context switching? Does synchronized method allow for context switching from one thread to another?</p>
  </li>
  </ol>
  <p>I apologise if any part of my question is confusing as I am relatively new to Java Spring/Spring Boot especially the concept of concurrency, multithreading etc. Please do let me know if you need me to clarify any part of my question.</p>