Java AtomicReference runInThread(final Runnable runnable)

Here you can find the source of runInThread(final Runnable runnable)

Description

run In Thread

License

Open Source License

Declaration

public static void runInThread(final Runnable runnable) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.concurrent.atomic.AtomicReference;

public class Main {
    public static void runInThread(final Runnable runnable) {
        final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
        Runnable exceptionGuard = new Runnable() {
            @Override//from   w  ww  .j  a v a2s. c om
            public void run() {
                try {
                    runnable.run();
                } catch (Throwable thr) {
                    exception.set(thr);
                }
            }
        };
        run(exceptionGuard);
        if (exception.get() != null) {
            throw new RuntimeException("Caught exception in thread", exception.get());
        }
    }

    private static void run(Runnable runnable) {
        Thread thread = startDaemonThread(runnable);
        try {
            thread.join();
        } catch (InterruptedException ie) {
            throw new RuntimeException(ie);
        }
    }

    private static Thread startDaemonThread(Runnable runnable) {
        Thread result = new Thread(runnable);
        result.setDaemon(true);
        result.start();
        return result;
    }
}

Related

  1. isTerminated(AtomicReference field)
  2. length(AtomicReferenceArray buf)
  3. mergeProperties(Properties... properties)
  4. pack(int count, Object[] array, AtomicReference edit, int idx)
  5. runInThread(final Runnable runnable)