From 1677a1d7d5d12fc93419241a04fe4202749512b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=B5=9C=EC=8A=B9=EC=9D=80?= Date: Tue, 27 Dec 2022 11:47:53 +0900 Subject: [PATCH] 2022-12-27-Tue-11:19-SingletonContainerTest --- .../hello/core/singleton/StatefulService.java | 16 ++++++++ .../core/singleton/StatefulServiceTest.java | 38 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 src/test/java/hello/core/singleton/StatefulService.java create mode 100644 src/test/java/hello/core/singleton/StatefulServiceTest.java diff --git a/src/test/java/hello/core/singleton/StatefulService.java b/src/test/java/hello/core/singleton/StatefulService.java new file mode 100644 index 0000000..42c8997 --- /dev/null +++ b/src/test/java/hello/core/singleton/StatefulService.java @@ -0,0 +1,16 @@ +package hello.core.singleton; + +public class StatefulService { + + private int price; // 싱글톤 패턴에서 공유 필드는 정말 조심해서 쓰고 늘 stateless 상태로 쓰자 + + public void order(String name, int price) { + System.out.println("price = " + price + "name = " + name); + this.price = price; + } + + public int getPrice() { + return price; // 여기가 문제 + } + +} diff --git a/src/test/java/hello/core/singleton/StatefulServiceTest.java b/src/test/java/hello/core/singleton/StatefulServiceTest.java new file mode 100644 index 0000000..c6b5e37 --- /dev/null +++ b/src/test/java/hello/core/singleton/StatefulServiceTest.java @@ -0,0 +1,38 @@ +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; + +class StatefulServiceTest { + + @Test + void statefulServiceSingleton() { + ApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class); + StatefulService statefulService1 = ac.getBean(StatefulService.class); + StatefulService statefulService2 = ac.getBean(StatefulService.class); + + // Thread A : A 사용자가 10,000원 주문 + statefulService2 .order("userA", 10000); + + // Thread B : B 사용자가 20,000원 주문 + statefulService2.order("userB", 20000); + + // Thread : 사용자 A 주문 금액 조회 : 20,000원이 나오므르 문제 발생 + 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(); + } + + } +} \ No newline at end of file