Back-End/Spring

[Spring][스프링 기본편] - 17. 싱글톤 방식의 주의점

얄루몬 2022. 1. 26. 11:09

1. 싱글톤 컨테이너 사용 시 주의점

[공유 필드의 값을 클라이언트가 변경하여 발생한 문제상황]

package hello.core.singleton;

public class StatefulService {

    private int price;
    public void order(String name, int price){
        System.out.println("name = " + name + " price = " + price);
        this.price = price; //여기가 문제
    }
    public int getPrice(){
        return price;
    }
}
import org.springframework.context.annotation.Bean;

import static org.assertj.core.api.Assertions.assertThat;
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);
        //ThreadA : B사용자 20000원 주문
        statefulService2.order("userB",20000);

        //ThreadA: A 주문 금액 조회
        int price = statefulService1.getPrice();
        System.out.println("price = " + price);
        //A가 주문하고 조회하는 사이에 B가 끼어드는 것

        assertThat(statefulService1.getPrice()).isEqualTo(20000);
    }
    static class TestConfig{
        @Bean
        public StatefulService statefulService(){
            return new StatefulService();
        }
    }
}

 

 

[결과]

 

A가 주문하고 주문을 조회하는 사이에 B가 끼어드는 상황인데 이때 문제가 되는 것은 둘은 같은 객체를 참조하기 때문에 값이 갈아치기 된다는 것이다. 그렇다면 우리는 이를 해결하기 위해서는 어떻게 코드 수정을 해야할까?

 

[구체적인 상황설명]

A필드에 10000원을 넣고 this.price =price; 때문에 price값에 10000원이 들어가 있다가 

B가 필드에 20000원을 넣어 this.price=price; 때문에 price의 값이 20000만원으로 바뀌어 결과적으로 20000만원이 출력되는 상황

 

2. 해결

[지역변수의 사용으로 클라이언트가 공유 필드의 변경을 할 수 없게 하자]

package hello.core.singleton;

public class StatefulService {

    private int price;
    public int order(String name, int price){
        System.out.println("name = " + name + " price = " + price);
        //this.price = price; //여기가 문제
        return price;
    }
    public int getPrice(){
        return price;
    }
}
package hello.core.singleton;

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.assertj.core.api.Assertions.assertThat;
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원 주문
        int userAprice = statefulService1.order("userA",10000);
        //ThreadA : B사용자 20000원 주문
        int userBprice = statefulService2.order("userB",20000);

        //ThreadA: A 주문 금액 조회
        System.out.println("price = " + userAprice);
        //A가 주문하고 조회하는 사이에 B가 끼어드는 것

        //assertThat(statefulService1.getPrice()).isEqualTo(20000);
    }
    static class TestConfig{
        @Bean
        public StatefulService statefulService(){
            return new StatefulService();
        }
    }
}

  • 실제 쓰레드를 사용하지 않고 단순하게 설명을 진행하였다고 한다.
  • 공유 필드는 꼭 무상태로 설계해야 한다!!

 

 

 

3. 싱글톤 방식의 주의점

  • 싱글톤 패턴이든, 스프링 같은 싱글톤 컨테이너를 사용하든, 객체 인스턴스를 하나만 생성해서 공유하는 싱글톤 방식은 여러 클라이언트가 하나의 같은 객체 인스턴스를 공유하기 때문에 싱글톤 객체는 상태를 유지(stateful)하게 설계하면 안된다.

 

  • 무상태(stateless)로 설계해야 한다!
    • 특정 클라이언트에 의존적인 필드가 있으면 안된다.
    • 특정 클라이언트가 값을 변경할 수 있는 필드가 있으면 안된다!
    • 가급적 읽기만 가능해야 한다.
    • 필드 대신에 자바에서 공유되지 않는, 지역변수, 파라미터, ThreadLocal 등을 사용해야 한다.

 

  • 스프링 빈의 필드에 공유 값을 설정하면 정말 큰 장애가 발생할 수 있다!!!

 

 

 

4. 출처

https://inf.run/7GX1

 

스프링 핵심 원리 - 기본편 - 인프런 | 강의

스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다., - 강의 소개 | 인프런...

www.inflearn.com