import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeoutException;

/**
 * {@link <a href=
 * "https://[Log in to view URL]"
 * target= "_blank"></a>}
 * 
 * @author itammb ( Italia Massimiliano Buscati )
 * @version JDK 1.15
 *
 */
class Main {
		private static class CallableTask implements Callable<String> {
		private String task;
		private SimpleDateFormat ft;

		public CallableTask(String task) {
			this.task = task;
			ft = new SimpleDateFormat("hh:mm:ss");
		}

		/**
		 * @see Callable#call()
		 * 
		 */
		@Override
		public String call() throws Exception {
			try {
				for (int i = 0; i <= 3; i++) {
					if (i == 0)
						log("INIT");
					else
						log("EXECUTE - STEP-" + i);

					Thread.sleep(1000);
				}

				log("COMPLETE");
			} catch (InterruptedException ie) {
				log("KILL");
				ie.printStackTrace();
			}

			return "TASK [" + task + "] return : " + ft.format(new Date());
		}

		private void log(String status) {
			System.out.println(task + " - " + status + " - " + ft.format(new Date()));
		}

		@Override
		public String toString() {
			return "CallableTask [task=" + task + ", hashCode()=" + hashCode() + "]";
		}
	}
	
	public static class SquareCalculator {    
	    	    
		/**
		 * @see ExecutorService#submit(Callable)
		 * 
		 */
	    public Future<Integer> calculate(Integer input, ExecutorService executor) {        
	        return executor.submit(() -> {
	            Thread.sleep(1000);
	            return input * input;
	        });
	    }
	}

	private static class UniTest {
		/**
		 * @see FutureTask#FutureTask(Callable)
		 * 
		 */
		public void simulateCallableTask() throws InterruptedException, ExecutionException {
			List<FutureTask<String>> buffer = new ArrayList<FutureTask<String>>();

			// creazione di un thread-pools con riciclo dei task
			ExecutorService pool = Executors.newCachedThreadPool();

			for (int i = 0; i < 10; i++) {
				FutureTask<String> task = new FutureTask<String>(new CallableTask("task " + i));
				buffer.add(task);
				pool.submit(task);
			}

			for (FutureTask<String> task : buffer)
				if ((System.currentTimeMillis() % 2) == 0)
					// interrompe il processo in esecuzione
					task.cancel(true);
				else
					Thread.sleep(2);

			shutdown(pool);

			executeStatus(buffer);
		}

		private void shutdown(ExecutorService pool) throws InterruptedException {
			pool.shutdown();

			while (!pool.isTerminated())
				Thread.sleep(2);

			System.out.println("SHUTDOWN - OK");
		}

		private void executeStatus(List<FutureTask<String>> buffer) throws InterruptedException, ExecutionException {

			for (FutureTask<String> task : buffer)
				if (task.isCancelled())
					System.out.println(task.toString() + " - CANCELLED ");
				else {
					System.out.println(task.toString() + " - " + task.get());
				}
		}
		
		public void simulateExecutorCallable() throws InterruptedException, ExecutionException {
			// creazione di un thread-pools con un singolo task
		    ExecutorService pool = Executors.newSingleThreadExecutor();
		    
			Future<Integer> future = new SquareCalculator().calculate(10, pool);
	
			while(!future.isDone()) {
			    System.out.println("CALCULATING...");
			    Thread.sleep(300);
			}
	
			System.out.println("RESULT Object - " + future.get());
			
			shutdown(pool);
		}
	}

	public static void main(String args[]) throws InterruptedException, ExecutionException, TimeoutException {
		// Unit test - thread-pool con task annulabili e restituzione della computazione
		new UniTest().simulateCallableTask();
		
		// Unit test - passaggio di una interfaccia Callable ( sotto forma di funzione labda ) a un Executor 
		new UniTest().simulateExecutorCallable();
	}
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: