How does the default singleton Controller ensure that the Service in it is thread-safe?

@Controller
public class MyController {


    @Autowired
    MyService service;

    @RequestMapping("/test")
    @ResponseBody
    public String hello() {
        service.save();
        return "h";
    }
}

service
Apr.03,2021

service is a singleton, and whether there is a thread safety problem depends on the service itself.

  1. if the service method is thread-safe, then the whole is thread-safe
    when we write business methods, we usually get business data from redis or db, then operate on the data, and finally write the changes back to redis or db,. In this case, the concurrency problem is guaranteed by the underlying storage (redis, MySQL)
  2. .
  3. service method is non-thread safe, then it is non-thread safe
    if memory objects need to be preserved in business operations, such as shared objects in service, it will be troublesome and there are many cases. If the shared object is valid at the request level, you can create a new service object at each request; if the shared object spans multiple requests, you need to select a thread-safe implementation and transform the service method to thread-safe

in your case, service.save should store objects directly in the database without thread safety problems, and all concurrency problems are left to db management.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e55105-45314.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e55105-45314.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?