스프링 내부 컨테이너는 싱글톤 스코프 빈을 지원한다.
public class SharedClass {
private int x;
public void setX(int x){
this.x = x;
}
public void getX(){
return this.x;
}
}
SharedClass에 하나의 객체만 생성하였다고 생각해보자. 멀티 스레드 환경에서 sharedClass 에 동시에 접근할 때 예상되는 문제가 있었다. data consitency이다. 분명히 x값을 수정했는데 다시 보았을 때는 다른 값이 들어있을 수 있다.
SharedClass sc = new ShareClass();
//A client
sc.setX(3);
//B client
sc.setX(5);
//A client
System.out.println(sc.getX());
//Expected 3, Actual 5
syncronized, lock 등 동기화 매커니즘을 이용하여 해당 문제를 해결할 수 있는데, 스프링에서는 어떻게 빈을 관리할지 궁금하였다. 생각할 수 있는 방법은 두가지였다.
- 빈을 생성할 때 stateless 한게 만든다. (공유 필드를 없앤다. )
- stateful 한 빈을 따로 관리한다.
공식문서에서는 후자에 대한 이야기가 있었다.
you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.
모든 빈이 singleton scope으로 관리되는 것이 아니였다. stateless 빈만 싱글톤으로 관리되는 것이었다. singleton scope을 이용할 때 얻을 수 있는 메모리 효율성 및 이점을, prototype scope에서는 얻지 못하는 것이다.
그렇기에 일반적으로는 class 를 만들때 상태를 만들지 않는것이 유리하다.
[공식 문서]
https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html
4.4 Bean scopes
The other scopes, namely request, session, and global session are for use only in web-based applications (and can be used irrespective of which particular web application framework you are using, if indeed any). In the interest of keeping related concepts
docs.spring.io
'Backend > Java Spring' 카테고리의 다른 글
[Java] 제너릭(Generic) (0) | 2023.11.17 |
---|---|
[Java] 직렬화와 역직렬화 (0) | 2023.11.15 |
[Java] 공유 중인 가변 데이터 (0) | 2023.11.12 |
[Spring] @Transactional (2) | 2023.11.09 |