동기, 비동기, 블로킹, 논블로킹 정리!

김수호·2024년 12월 6일
post-thumbnail

동기(Synchronous)/비동기(Asynchronous)

1. 동기

현재 작업을 끝내고 나서야 다른 작업을 할 수 있습니다.

public class Main {

    public static void main(String[] args) throws IOException {
        System.out.println("Start reading file ...");
        String result = readFile();  
        System.out.println("File read complete: " + result);
        System.out.println("Next job");
    }

    private static String readFile() throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader("C:\\study\\study\\Synchronous\\src\\main\\resources\\sample.txt"))) {
            String line = reader.readLine();
            return line;
        }
    }
}

결과

Start reading file ...
File read complete: Hello, this is a test file!
Next job

2. 비동기

현재 작업을 진행하면서 다른 쓰레드로 작업을 실행할 수 있습니다. 결과는 콜백을 통해 받습니다.

public class Main {

    public static void main(String[] args) {
        System.out.println("Start reading file asynchronously...");

        CompletableFuture.supplyAsync(() -> {
            try {
                return readFile();  // 파일을 읽는 작업을 비동기적으로 수행
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }).thenAccept(result -> System.out.println("File read complete: " + result));
        System.out.println("Next job");

        try {
            Thread.sleep(1000); 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static String readFile() throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader("C:\\study\\study\\Synchronous\\src\\main\\resources\\sample.txt"))) {
            String line = reader.readLine();
            return line;
        }
    }
}

결과

Start reading file asynchronously...
Next job
File read complete: Hello, this is a test file!

블로킹과 논블로킹

  1. 블로킹

    현재 작업이 완료 될때까지 대기하는 방식이므로 I/O 작업중 다른 작업을 같이 진행할 수 없습니다.

  2. 논블로킹

    현재 작업을 진행하는 동안 다른 작업을 처리할 수 있습니다.

비동기와 논블로킹 차이

  • 비동기

    • 비동기는 "작업을 다른 스레드에서 처리"하는 방식입니다. 즉, 한 작업이 끝날 때까지 기다리지 않고, 다른 작업을 병렬로 처리합니다.

    • 예시
      스레드 1이 DB에 접근하여 데이터를 읽고 있다고 가정합니다.
      스레드 2는 DB와 관계없이 다른 작업을 합니다.
      스레드 1의 작업이 끝나면, 그때 스레드 2에서 그 결과를 콜백으로 받거나, 나중에 처리할 수 있습니다.

    • 처리방식
      비동기의 경우 스레드가 완료를 기다리지 않고, 결과를 콜백이나 Future를 통해 받습니다.

  • 논블로킹

    • 논블로킹은 "자원을 기다리지 않고, 자원에 접근할 수 없으면 다른 일을 한다"는 방식입니다. 자원을 요청했을 때, 만약 자원이 사용 중이라면, 대기하지 않고 다른 작업을 합니다.

    • 예시
      스레드 1이 DB에 접근하려고 합니다. DB가 바쁘면, 스레드 1은 대기하지 않고 다른 작업을 처리하다가, DB가 여유가 생기면 그때 작업을 완료합니다.
      스레드 2는 DB와 관계 없이 또 다른 작업을 처리합니다.

    • 처리방식
      논블로킹의 경우 쓰레드 Thread.start()와 Thread.join()으로 결과를 처리한다.

사용하는 방식

profile
정답을 모르지만 답을 찾는 법을 알고, 그 답을 찾아낼 것이다. 그럼 괜찮지 않은가? -크리스 가드너-

0개의 댓글