-
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.
- Loading branch information
Showing
2 changed files
with
55 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,15 @@ | ||
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; | ||
} | ||
} |
40 changes: 40 additions & 0 deletions
40
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,40 @@ | ||
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 사용자가 1만원 주문 | ||
statefulService1.order("userA", 10000); | ||
|
||
// ThreadB: B 사용자가 2만원 주문 | ||
statefulService1.order("userB", 20000); | ||
|
||
// ThreadA: A 사용자가 주문 금액 조회 | ||
int price = statefulService1.getPrice(); | ||
System.out.println("price = " + price); | ||
|
||
assertThat(statefulService1.getPrice()).isEqualTo(20000); | ||
} | ||
|
||
static class TestConfig { | ||
@Bean | ||
public StatefulService statefulService() { | ||
return new StatefulService(); | ||
} | ||
} | ||
|
||
|
||
} |