|
| 1 | +package example.concurrency.ch10; |
| 2 | + |
| 3 | +import java.util.concurrent.CountDownLatch; |
| 4 | +import java.util.concurrent.ExecutorService; |
| 5 | +import java.util.concurrent.Executors; |
| 6 | +import java.util.concurrent.TimeUnit; |
| 7 | +import org.junit.jupiter.api.Test; |
| 8 | +import org.springframework.beans.factory.annotation.Autowired; |
| 9 | +import org.springframework.boot.test.context.SpringBootTest; |
| 10 | + |
| 11 | +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) |
| 12 | +public class DeadLockTest { |
| 13 | + |
| 14 | + @Autowired |
| 15 | + private OuterService outerService; |
| 16 | + |
| 17 | + @Test |
| 18 | + public void testDeadLoc() throws InterruptedException { |
| 19 | + ExecutorService executorService = Executors.newFixedThreadPool(2); |
| 20 | + CountDownLatch startLatch = new CountDownLatch(1); |
| 21 | + CountDownLatch doneLatch = new CountDownLatch(2); |
| 22 | + |
| 23 | + System.out.println("=== 데드락 테스트 시작 ==="); |
| 24 | + |
| 25 | + // Thread 1 |
| 26 | + executorService.submit(() -> { |
| 27 | + try { |
| 28 | + startLatch.await(); // 동시 시작을 위한 대기 |
| 29 | + System.out.println("Thread-1 시작"); |
| 30 | + outerService.outerMethod(); |
| 31 | + System.out.println("Thread-1 완료"); |
| 32 | + } catch (Exception e) { |
| 33 | + System.err.println("Thread-1 에러: " + e.getMessage()); |
| 34 | + e.printStackTrace(); |
| 35 | + } finally { |
| 36 | + doneLatch.countDown(); |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + // Thread 2 |
| 41 | + executorService.submit(() -> { |
| 42 | + try { |
| 43 | + startLatch.await(); // 동시 시작을 위한 대기 |
| 44 | + System.out.println("Thread-2 시작"); |
| 45 | + outerService.outerMethod(); |
| 46 | + System.out.println("Thread-2 완료"); |
| 47 | + } catch (Exception e) { |
| 48 | + System.err.println("Thread-2 에러: " + e.getMessage()); |
| 49 | + e.printStackTrace(); |
| 50 | + } finally { |
| 51 | + doneLatch.countDown(); |
| 52 | + } |
| 53 | + }); |
| 54 | + |
| 55 | + // 잠시 대기 후 동시 실행 |
| 56 | + Thread.sleep(100); |
| 57 | + System.out.println("두 스레드 동시 시작!"); |
| 58 | + startLatch.countDown(); |
| 59 | + |
| 60 | + // 최대 30초 대기 (데드락이면 타임아웃) |
| 61 | + boolean completed = doneLatch.await(30, TimeUnit.SECONDS); |
| 62 | + |
| 63 | + if (!completed) { |
| 64 | + System.err.println("⚠️ 타임아웃 발생 - 데드락 가능성!"); |
| 65 | + } else { |
| 66 | + System.out.println("✅ 모든 스레드 정상 완료"); |
| 67 | + } |
| 68 | + |
| 69 | + executorService.shutdownNow(); |
| 70 | + } |
| 71 | +} |
0 commit comments