Home > Blockchain >  Is the Spring application multithreaded or not?
Is the Spring application multithreaded or not?

Time:04-09

I need to create several services in which endless cycles will be spinning, with the possibility of stopping them. It seems like it begs to implement everything in separate threads. I tried to create them in a Spring application by writing a small test application. The use of Spring in this application is due to the fact that you will have to connect a web interface to it.

@Service
public class FirstService
 public isStart = false;
 private action() {
    while (isStart) {
        ... 
    } 
 }
}
@Service
public class NextService
 public isStart = false;
 private action() {
    while (isStart) {
        ... 
    } 
 }
}

The service is started and stopped via controllers

@RestController
public class MyController {

  FirstService firstService;
  
  @PostMapping
  public ResponseEntity<?> post(@PathVariable(PARAM_ACTION) Integer action) {
    firstService.isStart = ...;
    ...
  }
  ...
}

It seems like everything works, i.e. it turns out that the application is multithreaded? Otherwise, everything would stop until the first action method is executed Question: Should I create a multithreaded application if everything is already working? Or is this not a very good solution and still need to be implemented using a standard solution with threads? Or maybe Spring has another ready-made solution for such cases as well?

CodePudding user response:

Depending on whether you’re using spring-web or spring-webflux, the default web server is Tomcat or Netty, respectively. Both are multithreaded. In fact, I don’t know of any web server in the market that isn’t. If you want to fine tune the thread pool, see https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html.

CodePudding user response:

Your service classes are usual class and not synchronized. any class in spring has a scope and by default they are singleton. In web spring just one thread is responsible for executing all your request but in webflux because of none blocking nature every idle thread is used to proceed the request. but if you want to write concurrent app you must use multi-threading mechanism like synchronize or locking solutions

  • Related