-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
2022-12-27-Tue-11:19-SingletonContainerTest
- Loading branch information
1 parent
20928dd
commit 1677a1d
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; // 여기가 문제 | ||
} | ||
|
||
} |
38 changes: 38 additions & 0 deletions
38
src/test/java/hello/core/singleton/StatefulServiceTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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(); | ||
} | ||
|
||
} | ||
} |