Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.concurrent.*;

public class Main {
    public static <T> T executeWithTimeout(Callable<T> task, int milliseconds) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Future<T> future = executor.submit(task);
        T result;
        try {
            result = future.get(milliseconds, TimeUnit.MILLISECONDS);
        } catch (Exception e) { //handle timeout and other exceptions
            e.printStackTrace();
            result = null;
        } finally {
            future.cancel(true);
        }
        return result;
    }
}