본문 바로가기

Java

[Spring] SingleTon 단점

반응형

싱글톤 방식의 주의점

  • 객체 인스턴스를 하나만 생성해서 공유하는 싱글톤 방식은 여러 클라이언트가 하나의같은 객체 인스턴스를 공유하기 때문에 싱글톤 객체는 상채를 유지하게 설계하면 안된다.
  • 무상태(stateless)로 설계해야 한다.
    • 특정 클라이언트에 의존적인 필드가 있으면 안된다.
    • 특정 클라이언트가 값을 변경할 수 있는 필드가 있으면 안된다.
    • 가급적 읽기만 가능해야한다.
    • 필드 대신에 자바에서 공유되지 않은 지역변수, 파라미터, threadLocal등을 사용해야 한다.
  • 스프링 빈의 필드에 공유 값을 설정하면 정말 큰 장애가 발생할 수 있다.
package hello.core.singleton;

import org.junit.jupiter.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 st1 = ac.getBean(StatefulService.class);
        StatefulService st2 = ac.getBean(StatefulService.class);

        //ThreadA : A사용자가 10000원 주문
        st1.order("userA", 10000);

        //ThreadA : B사용자가 20000원 주문
        st2.order("userB", 20000);

        //TreadA: 사용자A 주문금핵 조회
        int price = st1.getPrice();
        System.out.println("price = " + price);
        org.assertj.core.api.Assertions.assertThat(st1.getPrice()).isEqualTo(20000);
    }

    static class TestConfig{
        @Bean
        public StatefulService statefulService(){
            return new StatefulService();
        }
    }

}

st1 객체와 st2객체는 초기에 만들어진 StatefulService 객체를 같이 사용하고 있기 때문에 StatefulService객체의 price는 10000->20000으로 변경된다.
====이런 문제를 해결하기위해선 공유되지 않는 지역변수, 파라미터, ThreadLocal을 사용해야 한다====

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;
//    }
}

order 메서드를 파라미터 return으로 변경

package hello.core.singleton;

import org.junit.jupiter.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 st1 = ac.getBean(StatefulService.class);
        StatefulService st2 = ac.getBean(StatefulService.class);

        //ThreadA : A사용자가 10000원 주문
        st1.order("userA", 10000);

        //ThreadA : B사용자가 20000원 주문
        st2.order("userB", 20000);

        //TreadA: 사용자A 주문금핵 조회
        //int price = st1.getPrice();
        System.out.println("price = " + st1);
        org.assertj.core.api.Assertions.assertThat(st1).isNotEqualTo(20000);
    }

    static class TestConfig{
        @Bean
        public StatefulService statefulService(){
            return new StatefulService();
        }
    }

}

반응형

'Java' 카테고리의 다른 글

[Java] Lambda function 예제  (0) 2021.12.28
[Spring] Configuration N SingleTon  (0) 2021.12.27
[Spring] SingleTon  (3) 2021.12.24
[Spring] create Spring Container  (1) 2021.12.21
[Spring] IntelliJ 단축키 모음  (5) 2021.12.19