Skip to content

Commit

Permalink
2022-12-27-Tue-11:19-SingletonContainerTest
Browse files Browse the repository at this point in the history
  • Loading branch information
liberalwig committed Dec 27, 2022
1 parent 20928dd commit 1677a1d
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/test/java/hello/core/singleton/StatefulService.java
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 src/test/java/hello/core/singleton/StatefulServiceTest.java
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();
}

}
}

0 comments on commit 1677a1d

Please sign in to comment.