Supplier<T> interface

midas·2022년 5월 19일
1

Supplier 함수형 인터페이스

✨ Supplier

Supplier<T>매개변수를 받지 않고 단순하게 무엇인가를 반환 하는 역할을 합니다.

아래는 Supplier의 코드 입니다.

/**
 * Represents a supplier of results.
 *
 * <p>There is no requirement that a new or distinct result be returned each
 * time the supplier is invoked.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #get()}.
 *
 * @param <T> the type of results supplied by this supplier
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

🤔 Lazy Evaluation

Supplier<T>는 인터페이스는 get()을 통해서 Lazy Evaluation이 가능합니다.

바로 테스트 코드로 알아봅시다.

public class SupplierTest {

	long start = 0;     // 시간을 측정을 위한 변수

	@BeforeEach
	void setup() {
		start = System.currentTimeMillis();
	}

	@AfterEach
	void tearDown() {
		long time = (System.currentTimeMillis() - start) / 1000;
		System.out.println("Time taken: " + time + " second");
	}

    //== 얘는 누가봐도 3초씩 총 9초가 걸립니다. ==//
	@Test
	void testPrint() {
		printIndexOverZero(1, getDooly());
		printIndexOverZero(-1, getDooly());
		printIndexOverZero(-2, getDooly());
	}

    //== 그럼 Supplier를 사용했을 때 몇초가 걸릴 까요? 🤔 ==//
	@Test
	void testSupplier() {
		printIndexOverZeroUsingSupplier(1, this::getDooly);
		printIndexOverZeroUsingSupplier(-1, this::getDooly);
		printIndexOverZeroUsingSupplier(-2, this::getDooly);
	}

    //== [시간 측정 위한] 3초 딜레이 후 값 반환 ==//
	private String getDooly() {
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}

		return "dooly";
	}

    //== 2가지 방식의 출력 메서드  ==//
    // 1. String을 받아서 그대로 출력
	void printIndexOverZero(int index, String value) {
		if (index > 0) {
			System.out.println("Success print value: " + value);
		} else {
			System.out.println("Invalid");
		}
	}

    // 2. Supplier를 받아서 처리
	void printIndexOverZeroUsingSupplier(int index, Supplier<String> supplier) {
		if (index > 0) {
			System.out.println("Success print value: " + supplier.get());
		} else {
			System.out.println("Invalid");
		}
	}
}

위의 테스트 에서 supplierTest()는 총 몇초가 걸릴까요?

printIndexOverZeroUsingSupplier()에서 supplier는 .get()를 통해서 받은 메서드를 소비하게 되어 이 때만 함수가 실행되게 됩니다.
그래서 정답은 총 3초가 걸립니다.

이렇게 Lazy evaluation을 통해서 불필요한 연산을 줄일 수도 있습니다.

⚡️ 정리

  • Supplier는 매개변수가 없이 반환하는 역할
  • Lazy evaluation을 통해서 불필요한 연산을 줄일 수 있다.

🔖 참고

profile
BackEnd 개발 일기

0개의 댓글