Posted In: Pattern, Spring

Use of adapter pattern in Spring – CompletableToListenableFutureAdapter

Adapter pattern

Adapter pattern allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.
In this example adapter takes CompletableFuture as constructor argument and returns Spring ListenableFuture.

 

package com.example.spring.pattern;

import java.util.concurrent.CompletableFuture;

import org.springframework.util.concurrent.CompletableToListenableFutureAdapter;
import org.springframework.util.concurrent.ListenableFuture;

public class AdapterExample1 {

	public static void main(String[] args) {
		new AdapterExample1().proceed();
	}

	public void proceed() {
		System.out.println("AdapterExample1::proceed() started");
		try {
			CompletableFuture<String> future = CompletableFuture
			        .supplyAsync(this::method1);

			future.thenApply(this::method2);

			ListenableFuture<String> lfuture = new CompletableToListenableFutureAdapter<>(
			        future);
			System.out.println(lfuture.get());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String method1() {
		System.out.println("AdapterExample1::method1() started");
		return "method1";
	}

	private String method2(String a) {
		System.out.println(
		        "AdapterExample1::method2() started a=" + a);
		return a + "method2";
	}
}

Tags:

by , on July 24th, 2017

  • Categories