当前位置:网站首页>Is the controller a single instance or multiple instances? How to ensure the safety of concurrency
Is the controller a single instance or multiple instances? How to ensure the safety of concurrency
2022-07-03 22:42:00 【╱℡&▓】
answer :
controller The default is singleton , Don't use non static member variables , Otherwise, there will be data logic confusion . Because of the singleton, it's not thread safe .
Let's do a simple verification :
package com.riemann.springbootdemo.controller;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author riemann
* @date 2019/07/29 22:56
*/
@Controller
public class ScopeTestController {
private int num = 0;
@RequestMapping("/testScope")
public void testScope() {
System.out.println(++num);
}
@RequestMapping("/testScope2")
public void testScope2() {
System.out.println(++num);
}
} Let's first visit http://localhost:8080/testScope, The answer is 1;
Then we will visit http://localhost:8080/testScope2, The answer is 2.
Different values you get , This is thread unsafe .
Next we'll give controller There are many cases of increasing effect @Scope("prototype")
package com.riemann.springbootdemo.controller;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author riemann
* @date 2019/07/29 22:56
*/
@Controller
@Scope("prototype")
public class ScopeTestController {
private int num = 0;
@RequestMapping("/testScope")
public void testScope() {
System.out.println(++num);
}
@RequestMapping("/testScope2")
public void testScope2() {
System.out.println(++num);
}
} We are still the first to visit http://localhost:8080/testScope, The answer is 1;
Then we will visit http://localhost:8080/testScope2, The answer is still 1.
I believe it's not hard to find out :
Singleton is not safe , Will cause the attribute to be reused .
Solution
1、 Not in controller Define member variables in .2、 In case you have to define a non static member variable , By way of annotation @Scope(“prototype”), Set it to multi instance mode .3、 stay Controller Use in ThreadLocal Variable
Additional explanation
spring bean The scope is as follows 5 individual :
singleton: The singleton pattern , When spring establish applicationContext Container time ,spring Will want to initialize all instances of the scope , add lazy-init You can avoid preprocessing ;
prototype: Archetypal model , Each time through getBean Get the bean It will create a new instance , After creation spring It will no longer be managed ;
( The following is the web Only under the project )
request: To make web Everyone should understand request It's the domain of , That is, each request generates a new instance , and prototype The difference is that after creation , The next management ,spring Still monitoring ;
session: Every conversation , ditto ;
global session: Overall web Domain , Be similar to servlet Medium application.
边栏推荐
- Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?
- Wisdom tooth technology announced that it had completed the round D financing of US $100million and had not obtained a valid patent yet
- Unique in China! Alibaba cloud container service enters the Forrester leader quadrant
- ThreadLocal function, scene and principle
- This time, thoroughly understand bidirectional data binding 01
- Quick one click batch adding video text watermark and modifying video size simple tutorial
- Yyds dry goods inventory [practical] simply encapsulate JS cycle with FP idea~
- [golang] leetcode intermediate - alphabetic combination of island number and phone number
- Es6~es12 knowledge sorting and summary
- Preliminary analysis of smart microwave radar module
猜你喜欢

Shell script three swordsman awk

The difference between SRAM and DRAM

Teach you how to run two or more MySQL databases at the same time in one system

Sort merge sort

The overseas listing of Shangmei group received feedback, and brands such as Han Shu and Yiye have been notified for many times and received attention

IO flow review

Bluebridge cup Guoxin Changtian single chip microcomputer -- hardware environment (I)

How can enterprises and developers take advantage of the explosion of cloud native landing?

How to connect a laptop to a projector

Preliminary analysis of smart microwave radar module
随机推荐
To rotate 90 degrees clockwise and modify the video format
Leetcode: a single element in an ordered array
Programming language (2)
Teach you how to run two or more MySQL databases at the same time in one system
[SRS] build a specified version of SRS
股票炒股开户注册安全靠谱吗?有没有风险的?
Common problems in multi-threaded learning (I) ArrayList under high concurrency and weird hasmap under concurrency
(POJ - 2912) rochambau (weighted concurrent search + enumeration)
Redis single thread and multi thread
Ten minutes will take you in-depth understanding of multithreading. Multithreading on lock optimization (I)
[untitled]
Label coco format data and format data in the upper left corner and lower right corner are mutually converted
Summary of basic knowledge of exception handling
In VS_ In 2019, scanf and other functions are used to prompt the error of unsafe functions
pycuda._ driver. LogicError: explicit_ context_ dependent failed: invalid device context - no currently
Sow of PMP
Pan Yueming helps Germany's Rochester Zodiac custom wristwatch
IO flow review
Blue Bridge Cup Guoxin Changtian single chip microcomputer -- led lamp module (V)
Go Technology Daily (2022-02-13) - Summary of experience in database storage selection