jeudi 13 février 2014

Handling a RuntimeException in a Runnable (Thread)

 

package edu.test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class App {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    executor.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + " -> " + System.currentTimeMillis());
            throw new RuntimeException("exception");
        } catch (RuntimeException e) {
            Thread t = Thread.currentThread();
            t.getUncaughtExceptionHandler().uncaughtException(t, e);
        }
        }
    }, 0, 1000, TimeUnit.MILLISECONDS).get();

    System.out.println("exit");
    executor.shutdown();
    }
}