Java/12. 멀티 스레드 (Multi Thread)

★Day 18 : 스레드풀 - 콜백 방식의 작업 완료 통보★

pancakemaker 2021. 11. 11. 16:54

콜백(Callback) : 애플리케이션이 스레드에게 작업 처리를 요청한 후 다른 기능을 수행할 동안 스레드가 작업을 완료하면 특정 메소들르 자동 실행하는 기법

 

작업 완료 통보 얻기 : 블로킹 vs 콜백

블로킹 방식은 작업 처리를 요청한 후 작업이 완료될 때까지 블로킹되지만, 콜백 방식은 작업 처리를 요청한 후 결과를 기다릴 필요 없이 다른 기능을 수행할 수 있다.

 

콜백 객체 : CompletionHandler 인터페이스를 이용 → 콜백 메소드를 가지고 있는 객체

콜백하기 : 스레드에서 콜백 객체의 메소드 호출

 

CompletionHandler의 completed(), failed() 메소드

- completed() : 작업을 정상 처리 완료했을 때 호출되는 콜백 메소드

- failed() : 작업 처리 도중 예외가 발생했을 때 호출되는 콜백 메소드

Runnable task = new Runnable() {
   @Override
   public void run() {
      try {
         //작업 처리
         V result = ...;
         callback.completed(result, null); //작업을 정상 처리했을 때 호출
      } catch (Exception e) {
         callback.failed(e, null); //예외가 발생 했을 경우 호출
      }
   }
};

 

콜백 방식의 작업 완료 통보받기

package sec09.exam03_callback;

import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CallbackExample {
	//필드
	private ExecutorService executorService;
	
	//생성자
	public CallbackExample() {
		executorService = Executors.newFixedThreadPool(
				Runtime.getRuntime().availableProcessors()
		);
	}
	//콜백 메소드를 가진 CompletionHandler 객체 생성
	private CompletionHandler<Integer, Void> callback = 
			new CompletionHandler<Integer, Void>() {
				@Override
				public void completed(Integer result, Void attachment) {
					System.out.println("completed() 실행: " + result);
				}

				@Override
				public void failed(Throwable exc, Void attachment) {
					System.out.println("failed() 실행: " + exc.toString());
				}
		
		
	};
	
	public void doWork(String x, String y) {
		Runnable task = new Runnable() {
			@Override
			public void run() {
				try {
					int intX = Integer.parseInt(x);
					int intY = Integer.parseInt(y);
					int result = intX + intY;
					callback.completed(result, null); //정상 처리했을 경우 호출
				} catch(NumberFormatException e) {
					callback.failed(e, null); //예외 발생 시 호출
				}				
			}			
		};
		executorService.submit(task); //스레드풀에게 작업 처리 요청
	}
	
	public void finish() {
		executorService.shutdown();
	}
	
	
	public static void main(String[] args) {
		CallbackExample example = new CallbackExample();
		example.doWork("3", "3");
		example.doWork("3", "삼");
		example.finish();
	}
}
completed() 실행: 6
failed() 실행: java.lang.NumberFormatException: For input string: "삼"