Java Supplier 동작방식

Sun Ji·2023년 4월 15일
0

스터디

목록 보기
2/2

todo: Supplier의 동작방식과 어떤 상황에서 사용되는지 알아본다

Supplier<T>

  • 자바 8에 추가된 함수형 인터페이스
  • 함수형 인터페이스로, 매개변수를 받지 않고 단순히 어떠한 것을 반환하는 추상메서드(단일)가 존재한다.
@FunctionalInterface
public interface Supplier<T> {
	T get();
}

활용방식

Lazy Evaluation

계산의 결과값이 필요할 때까지 계산을 늦추는 기법.
필요없는 계산을 하지 않아 실행을 더 빠르게 할 수 있다.

  • ↔️ Busy Evaluation : 대부분의 프로그래밍언어에서 채택하는 방식

예시

  1. Supplier 사용하지 않았을 때
public class LazyEvaluation() {
	public static void main(String[] args) {
    	long startTime = System.currentTimeMillis();
        printIfValid(10, getValue()); // getValue() 실행1
        printIfValid(0, getValue()); // getValue() 실행2
        System.out.println("it tooks " + (System.currentTimeMillis() - startTime));
    }
    
    private String getValue() {
    	// 1만큼 지연 후 return
    	TimeUnit.SECONDS.sleep(1);
        
        return "valid";
    }
    
    private static void printIfValid(int number, String value) {
    	if (number > 0) {
        	System.println(value);
        } else {
        	System.out.println("invalid");
        }
    }
}

✔️ 결과

valid
invalid
it tooks 2
  1. Supplier를 사용하였을 때
public class LazyEvaluation() {
	public static void main(String[] args) {
    	long startTime = System.currentTimeMillis();
        printIfValid(10, () -> getValue()); // lazy evaluation
        printIfValid(0, () -> getValue()); // getValue는 해당값이 필요할 때 실행됨
        System.out.println("it tooks " + (System.currentTimeMillis() - startTime));
    }
    
    private String getValue() {
    	// 1만큼 지연 후 return
    	TimeUnit.SECONDS.sleep(1);
        
        return "valid";
    }
    
    private static void printIfValid(int number, Supplier<String> valueSupplier) {
    	if (number > 0) {
        	System.println(valueSupplier.get()); // 이 시점에서 getValue() 실행
        } else {
        	System.out.println("invalid");
        }
    }
}

✔️ 결과

valid
invalid
it tooks 1

참고:
https://hwan33.tistory.com/17
https://m.blog.naver.com/zzang9ha/222087025042
https://www.baeldung.com/java-callable-vs-supplier

profile
매일매일 삽질중...

0개의 댓글