/*
 * Java
 *
 * Copyright 2020 MicroEJ Corp. All rights reserved.
 * This library is provided in source code for use, modification and test, subject to license terms.
 * Any modification of the source code will break MicroEJ Corp. warranties on the whole library.
 */
package ej.basictool;

import java.lang.Thread.UncaughtExceptionHandler;

/**
 * Provides utility methods related to threads.
 */
public class ThreadUtils {

	private ThreadUtils() {
		// private constructor
	}

	/**
	 * Delays the execution of the current thread. This convenience method may be used instead of
	 * {@link Thread#sleep(long)} to avoid the necessity of catching the {@link InterruptedException}.
	 *
	 * @param millis
	 *            the execution delay, in milliseconds.
	 */
	public static void sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Handles an exception which has not been caught in a particular scope. If the
	 * {@link Thread#getUncaughtExceptionHandler() UncaughtExceptionHandler of the current thread} has been set, it is
	 * used to handle the exception. If not set, the {@link Thread#getDefaultUncaughtExceptionHandler() default
	 * UncaughtExceptionHandler} is used instead. If not set either, the stack trace of the exception is printed.
	 *
	 * The following example shows how this method may be used:
	 *
	 * <pre>
	 * try {
	 * 	connectionListener.onDisconnected();
	 * } catch (Exception e) {
	 * 	ThreadUtils.handleUncaughtException(e);
	 * }
	 * </pre>
	 *
	 * @param e
	 *            the exception to handle.
	 */
	public static void handleUncaughtException(Exception e) {
		// get uncaught exception handler
		Thread currentThread = Thread.currentThread();
		UncaughtExceptionHandler handler = currentThread.getUncaughtExceptionHandler();
		if (handler == null) {
			handler = Thread.getDefaultUncaughtExceptionHandler();
		}

		// handle exception
		if (handler != null) {
			handler.uncaughtException(currentThread, e);
		} else {
			e.printStackTrace();
		}
	}
}
