람다식의 변수값은 final, 그 이유?

Web Development assistant·2023년 11월 19일
0

# java

목록 보기
17/17

답 : 멀티 스레드 환경에서 스레드의 안전성을 보장하기 위함, 람다식은 병렬로 사용가능하기 때문

스레드 간의 경쟁 상태(Race Condition)와 같은 문제를 해결하고, 데이터의 일관성과 안전성을 보장하기 위해 사용됩니다.
자바의 '스레드 한정(Thread Comfinement)' 기법(또는 원칙)을 위배하지 않기 위함이라고도 한단다..

package 이것이자바다.람다식;

public class SynchronizedExample {
	private static int sharedCounter = 0;

    public static void main(String[] args) {
        Runnable incrementTask = () -> {
            for (int i = 0; i < 100000; i++) {
                synchronized (SynchronizedExample.class) {
                    sharedCounter++; // 동기화된 코드 블록, 경쟁상태를 해결, 동기화된 코드블록으로 공유자원에 대한 접근을 제어
                }
            }
        };

        Thread thread1 = new Thread(incrementTask);
        Thread thread2 = new Thread(incrementTask);

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("최종 결과: " + sharedCounter);
    }
}

/**
 * 
 * 아래의 코드에서 sharedCounter 값이 매번 다른 이유??
 * 
 * sharedCounter++은 세 가지 연산(읽기, 증가, 쓰기)을 수행합니다.
	스레드 1이 sharedCounter 값을 읽고 증가를 시도하고, 아직 쓰기가 이루어지지 않은 상태에서 스레드 2가 같은 값을 읽고 증가를 시도할 수 있습니다.
	스레드 1과 스레드 2가 각각 증가한 값을 쓰기 시도할 때, 한 스레드의 결과가 덮어씌워져서 마지막에 쓴 값만 남게 됩니다.
	이러한 상황이 반복되면서 각 스레드가 공유 자원에 접근하고 수정하는 과정에서 예측할 수 없는 값을 가질 수 있습니다.
 */
//public class SynchronizedExample {
//    private static int sharedCounter = 0;
//
//    public static void main(String[] args) {
//        // 여러 스레드가 공유된 자원에 동시에 접근하고 수정하는 상황을 시뮬레이션
//        Runnable incrementTask = () -> {
//            for (int i = 0; i < 100000; i++) {
//                sharedCounter++; // 공유된 자원에 접근하고 수정
//            }
//        };
//
//        Thread thread1 = new Thread(incrementTask);
//        Thread thread2 = new Thread(incrementTask);
//
//        thread1.start();
//        thread2.start();
//
//        try {
//            thread1.join();
//            thread2.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//        System.out.println("최종 결과: " + sharedCounter);
//    }
//}

0개의 댓글