동기화의 기능

  1. 배타적 실행
  1. 안정적 통신

가변데이터와 동기화

공유 중인 가변 데이터를 동기화 시켜주지 않으면 문제가 발생한다.

원자적 자원(boolean)에 접근하는 코드이다.

의도는 1초뒤에 멈추는 코드를 작성하였다.

package com.example.teststpringjava;

import java.util.concurrent.TimeUnit;

public class Sync {
    private static boolean stopRequested;

    public static void main(String[] args) throws InterruptedException {
        Thread backgroundThread = new Thread(() -> {
            int i = 0;
            while (!stopRequested)
                i++;
        });

        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }
}

Q. 이 코드는 몇 초 뒤에 종료될까?

JVM은 위의 코드를 hoisting(끌어올리기) 기법에 의해 아래처럼 최적화를 진행한다.

public static void main(String[] args) throws InterruptedException {
        Thread backgroundThread = new Thread(() -> {
            int i = 0;
            if (!stopRequested) {
                while (true)
                    i++;
            }
        });

        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }

따라서 해당 코드는 종료되지 않는다.