원지의 개발
article thumbnail
728x90

5. 싱글톤

  • (순수한 DI컨테이너)AppConfig는 호출할 때마다 다른 객체를 생성
  • 고객 트래픽이 초당 100이 나오면 초당 100개 객체가 생성되고 소멸 = 메모리 낭비가 심함
  • 해당 객체가 딱 1개 생성되고, 공유하도록 설계 = 싱글톤 패턴

싱글톤 패턴

  • 싱글톤 패턴 구현 방법은 여러가지
  • 객체 인스턴스를 2개 이상 생성되지 못하도록 만듦
package hello.core.singleton;

import static org.junit.jupiter.api.Assertions.*;

class SingletonService {

	private static final SingletonService instance = new SingletonService();
	
	public static SingletonService getInstance() {
		return instance;
	}

	//생성자
	private SingletonService() {
	}

	public void logic() {
		System.out.println("싱글톤 객체 로직 호출");
	}
}
  • private 생성자 사용해서 외부에서 임의로 new 키워드를 사용하지 못하도록 막기
  • instance가 먼저 static 영역으로 가면서 새로운 객체 생성
  • getInstance() 메서드는 instance 변수가 private 이므로 외부에서 접근하지 못하니까 public으로 만들고, 생성자와 멤버변수가 private이기 때문에 static 메서드가 됨
더보기
package hello.core.singleton;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import hello.core.AppConfig;
import hello.core.member.MemberService;

class SingletonTest {

	@Test
	@DisplayName("스프링 없는 순수한 DI 컨테이너")
	void pureContainer() {
		AppConfig appConfig = new AppConfig();
		//1. 조회: 호출할 때 마다 객체를 생성
		MemberService memberService1 = appConfig.memberService();
		
		//2. 조회: 호출할 때 마다 객체를 생성
		MemberService memberService2 = appConfig.memberService();
		
		//참조값이 다른 것을 확인
		System.out.println("memberService1 = " + memberService1);
		System.out.println("memberService2 = " + memberService2);
		
		//memberService1 != memberService2
		assertThat(memberService1).isNotSameAs(memberService2);
	}
	
	@Test
	@DisplayName("싱글톤 패턴을 적용한 객체 사용")
	void singletonServiceTest() {
		
		//private으로 생성자를 막음 → 컴파일 오류 발생
		SingletonService singletonService1 = SingletonService.getInstance();
		SingletonService singletonService2 = SingletonService.getInstance();
		
		System.out.println(singletonService1);
		System.out.println(singletonService2);
		
		assertThat(singletonService1).isSameAs(singletonService2);
		//same ==
		//equal
	}
}
  • new SingletonService로 만들지 못함

싱글톤 컨테이너

  • 스프링 컨테이너를 싱글톤 패턴을 적용하지 않아도, 객체 인스턴스를 싱글톤으로 관리
  • 스프링 컨테이너 == 싱글톤 컨테이너 역할, 싱글톤 객체를 생성하고 관리하는 기능을 싱글톤 레지스트리라고 함
package hello.core.singleton;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import hello.core.AppConfig;
import hello.core.member.MemberService;

class SingletonTest {

	@Test
	@DisplayName("스프링 없는 순수한 DI 컨테이너")
	void pureContainer() {
		//AppConfig appConfig = new AppConfig();
		ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
		
		//1. 조회: 호출할 때 마다 객체를 생성
		MemberService memberService1 = ac.getBean("memberService", MemberService.class);
		
		//2. 조회: 호출할 때 마다 객체를 생성
		MemberService memberService2 = ac.getBean("memberService", MemberService.class);
		
		//참조값이 다른 것을 확인
		System.out.println("memberService1 = " + memberService1);
		System.out.println("memberService2 = " + memberService2);
		
		//memberService1 != memberService2
		assertThat(memberService1).isSameAs(memberService2);
	}
	
	@Test
	@DisplayName("싱글톤 패턴을 적용한 객체 사용")
	void singletonServiceTest() {
		
		//private으로 생성자를 막음 → 컴파일 오류 발생
		SingletonService singletonService1 = SingletonService.getInstance();
		SingletonService singletonService2 = SingletonService.getInstance();
		
		System.out.println(singletonService1);
		System.out.println(singletonService2);
		
		assertThat(singletonService1).isSameAs(singletonService2);
		//same ==
		//equal
	}
}

싱글톤 주의점

  • 싱글톤으로 price 필드는 공유되는 필드(A랑 B랑 같은 인스턴스 사용)로 특정 클라이언트가 값을 변경
  • 특정 클라이언트에게 의존적인 필드가 있으면 안 됨
  • 공유 필드는 항상 조심해야하며, 무상태로 설계해야 함
  • 필드 대신 지역변수, 파라미터, ThreadLocal 등을 사용해야 함

무상태로 설계해야 하는 이유

더보기

"무상태" 라는 말은 멤버 변수를 가지지 않는 것을 의미합니다.

싱글톤을 사용할때는 왜 무상태로 설계를 해야하는가?
싱글톤이라는 것이 사용자 요청대로 객체를 생성하는 것이 아닌, 객체를 단 하나만 생성해서 사용하는 패턴입니다. 싱글톤 객체에 멤버 변수가 존재하면, 여러 스레드에서 하나의 멤버 변수에 접근할 수 있게됩니다. 그렇게 되면 A 스레드에서 멤버 변수1의 값을 사용해서 비즈니스 로직을 수행하는 동안, B 스레드에서 멤버 변수1의 값을 변경하면 A 스레드에서 수행중이던 비즈니스 로직에 이상이 생길 수 있겠죠?
이러한 이슈 말고도 다른 이유가 있겠지만, 싱글톤을 사용할 때는 무상태로 설계해야합니다.

 

출처: 인프런 커뮤니티

package hello.core.singleton;

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;
	}
}
package hello.core.singleton;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

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);
		
		assertThat(statefulService1.getPrice()).isEqualTo(20000);
	}
	
	static class TestConfig { //new AnnotationConfigApplicationContext에서 참조하기 위해 static 붙음
		@Bean
		public StatefulService statefulService() {
			return new StatefulService();
		};
	}
}
  • price 필드를 사용하고, 해당 필드의 값을 변경하고 있는 order 메서드가 클라이언트

무상태 설계 코드

package hello.core.singleton;

class StatefulService {
	
	public int order(String name, int price) {
		System.out.println("name = " + name + " price = " + price);
		return price;
	}
}
package hello.core.singleton;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

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);
		//ThreadB: B사용자가 20000원 주문
		int userBPrice = statefulService2.order("userB", 20000);
		
		//ThreadA: 사용자A 주문 금액 조회
		System.out.println("price = " + userAPrice);
	}
	
	static class TestConfig { //new AnnotationConfigApplicationContext에서 참조하기 위해 static 붙음
		@Bean
		public StatefulService statefulService() {
			return new StatefulService();
		};
	}
}

@Configuration

  • AppConfig.class를 보면 (다섯 번 호출할 것 같지만) 세 번만 호출함

  • 순수한 클래스라면 class hello.core.AppConfig 처럼 출력되어야 함
  • class hello.core.AppConfig$$EnhancerBySpringCGLIB$$bd479d70 이렇게 출력이 되는데
    xxxCGLIB가 붙으면 내가 만든게 아니라 바이트코드 조작 라이브러리를 사용해서 AppConfig 클래스를 상속받은 임의의 다른 클래스를 만들고, 그 다른 클래스를 스프링 빈으로 등록한 것
싱글톤 보장 방법
@Bean이 붙은 메서드마다 이미 스프링 빈이 존재하면 존재하는 빈을 반환하고, 스프링 빈이 없으면 생성해서 스 프링 빈으로 등록하고 반환하는 코드가 동적으로 만들어짐

@Configuration 적용하지 않고 @Bean만 적용시

  • 바이트코드를 조작하는 CGLIB 기술을 사용한 싱글톤을 보장하지 못하므로

call AppConfig.memberService
call AppConfig.memberRepository
call AppConfig.orderService
call AppConfig.memberRepository
call AppConfig.memberRepository

  • memberRepository가 3번 출력되며, 이는 각각 다른 인스턴스임
스프링 설정 정보는 항상 @Configuration 을 사용하자
728x90
profile

원지의 개발

@원지다

250x250