Callback · Functional · Java

Callback Function in Java

                                                  The following program simulates the call back function feature in Java. This program has been written using functional interface and Callable feature in java. This can be understood by reading below code directly.

/**
 * The following program explains the mimicking of callback  function in java. 
 */
package java8pract;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Prabhu KVN
 *
 */
public class CallBackFunction {

	ExecutorService executorservice = Executors.newFixedThreadPool(2);

	/**
	 * 
	 */
	public CallBackFunction() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CallBackFunction fun = new CallBackFunction();
		double val = 100;

		// handleResult is the call back function
		fun.findRoot(val, new ResultHandler() {

			@Override
			public void handleResult(double n) {
				// TODO Auto-generated method stub
				System.out.println("Root of " + val + " is " + n);
			}
		});
		System.out.println("Finding root in progress...");

	}

	public void findRoot(double number, ResultHandler handler) {

		RootFinder finder = new RootFinder(number, handler);

		executorservice.submit(finder);
		executorservice.shutdown();

	};

}

@FunctionalInterface
interface ResultHandler {
	public void handleResult(double n);
}

/**
 * A callable function which will execute a login and will call handler to
 * propagate the logic to an handler.
 * 
 * @author prabhu kvn
 *
 */
class RootFinder implements Callable<Double> {
	double number;
	ResultHandler handler;

	public RootFinder(double number, ResultHandler handler) {
		// TODO Auto-generated constructor stub
		this.number = number;
		this.handler = handler;
	}

	@Override
	public Double call() throws Exception {
		// TODO Auto-generated method stub
		double sqrt = Math.sqrt(number);
		handler.handleResult(sqrt);

		return sqrt;
	}
}