싱글톤 패턴이든, 스프링 같은 싱글톤 컨테이너를 사용하든, 객체 인스턴스를 하나만 생성해서 공유하는 싱글톤 방식은 여러 클라이언트가 하나의 같은 객체 인스턴스를 공유하기 때문에 싱글톤 객체는 상태를 유지(stateful)하게 설계하면 안된다.
무상태(stateless)로 설계해야 한다!
StatefulService를 위와 같이 만들고,
package hello.core.singleton;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import static org.junit.jupiter.api.Assertions.*;
class StatefulServiceTest {
@Test
void statefulServiceSingleton() {
ApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class);
StatefulService statefulService1 = ac.getBean(StatefulService.class);
StatefulService statefulService2 = ac.getBean(StatefulService.class);
//ThreadA : A사용자가 10000원 주문
statefulService1.order("userA", 10000);
//ThreadB : B사용자가 20000원 주문
statefulService2.order("userB", 20000);
//ThreadA : 사용자A 주문 금액 조회
int price = statefulService1.getPrice();
System.out.println("price = " + price);
Assertions.assertThat(statefulService1.getPrice()).isEqualTo(20000);
}
static class TestConfig {
@Bean
public StatefulService statefulService() {
return new StatefulService();
}
}
}
테스트 코드를 위와같이 만들었다.
A사용자가 10000원을 주문하면 싱글톤 컨테이너이므로 StatefulService의 price필드에 10000이 저장되는데, B사용자가 20000원을 주문하면 price필드 값이 10000에서 20000으로 변경된다.
이런방식으로 하면 치명적인 결과를 초래하므로 스프링 빈은 항상 무상태(stateless)로 설계해야 한다.
order메서드의 리턴을 price가 되게 수정하고,
userAPrice라는 지역변수를 사용해서 출력하면
잘 나오는것을 확인할 수 있다.