001/**
002 *
003 * Copyright 2014-2018 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.util;
018
019import java.util.logging.Level;
020import java.util.logging.Logger;
021
022public class Async {
023
024    /**
025     * Creates a new thread with the given Runnable, marks it daemon, starts it and returns the started thread.
026     *
027     * @param runnable TODO javadoc me please
028     * @return the started thread.
029     */
030    public static Thread go(Runnable runnable) {
031        Thread thread = daemonThreadFrom(runnable);
032        thread.start();
033        return thread;
034    }
035
036    /**
037     * Creates a new thread with the given Runnable, marks it daemon, sets the name, starts it and returns the started
038     * thread.
039     *
040     * @param runnable TODO javadoc me please
041     * @param threadName the thread name.
042     * @return the started thread.
043     */
044    public static Thread go(Runnable runnable, String threadName) {
045        Thread thread = daemonThreadFrom(runnable);
046        thread.setName(threadName);
047        thread.start();
048        return thread;
049    }
050
051    public static Thread daemonThreadFrom(Runnable runnable) {
052        Thread thread = new Thread(runnable);
053        thread.setDaemon(true);
054        return thread;
055    }
056
057    /**
058     * Like {@link Runnable}, but allows the <code>runOrThrow()</code> method to throw an exception.
059     * <p>
060     * If the exception is an instance of {@link RuntimeException}, then it will be re-thrown, otherwise <b>it will be
061     * simply logged.</b>
062     */
063    public abstract static class ThrowingRunnable implements Runnable {
064
065        public static final Logger LOGGER = Logger.getLogger(ThrowingRunnable.class.getName());
066
067        @Override
068        public final void run() {
069            try {
070                runOrThrow();
071            }
072            catch (Exception e) {
073                if (e instanceof RuntimeException) {
074                    throw (RuntimeException) e;
075                }
076                LOGGER.log(Level.WARNING, "Caught Exception", e);
077            }
078        }
079
080        public abstract void runOrThrow() throws Exception;
081    }
082}