Example usage for java.lang Thread setUncaughtExceptionHandler

List of usage examples for java.lang Thread setUncaughtExceptionHandler

Introduction

In this page you can find the example usage for java.lang Thread setUncaughtExceptionHandler.

Prototype

public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) 

Source Link

Document

Set the handler invoked when this thread abruptly terminates due to an uncaught exception.

Usage

From source file:edu.umn.cs.sthadoop.operations.HSPKNNQ.java

public static void main(String[] args) throws IOException {

    //./hadoop jar /export/scratch/louai/idea-stHadoop/st-hadoop-uber.jar pknn /mntgIndex/yyyy-MM-dd/2017-08-03 /pknn k:2 point:-78.9659,35.7998 shape:edu.umn.cs.sthadoop.mntg.STPointMntg -overwrite  
    //    args = new String[8];
    //    args[0] = "/export/scratch/mntgData/mntgIndex";
    //    args[1] = "/export/scratch/mntgData/pknn";
    //    args[2] = "-overwrite";
    //    args[3] = "k:10";
    //    args[4] = "point:-78.9659063204100,35.7903907684998";
    //    args[5] = "shape:edu.umn.cs.sthadoop.trajectory.STPointTrajectory";
    //    args[6] = "interval:2017-08-03,2017-08-04";
    //    args[7] = "-overwrite";
    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();/* www. j av a 2  s .  c  om*/
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }

    if (params.get("interval") == null) {
        System.err.println("Temporal range missing");
        printUsage();
        System.exit(1);
    }

    TextSerializable inObj = params.getShape("shape");
    if (!(inObj instanceof STPoint)) {
        if (!(inObj instanceof STRectangle)) {
            LOG.error("Shape is not instance of STPoint or instance of STRectangle");
            printUsage();
            System.exit(1);
        }

    }

    // path to the spatio-temporal index.
    List<Path> STPaths = new ArrayList<Path>();

    try {
        STPaths = STRangeQuery.getIndexedSlices(params);

    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    for (Path input : STPaths) {

        final Path inputFile = input;
        int count = params.getInt("count", 1);
        double closeness = params.getFloat("closeness", -1.0f);
        final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count];
        final FileSystem fs = inputFile.getFileSystem(params);
        final int k = params.getInt("k", 1);
        int concurrency = params.getInt("concurrency", 100);
        if (k == 0) {
            LOG.warn("k = 0");
        }

        if (queryPoints.length == 0) {
            printUsage();
            throw new RuntimeException("Illegal arguments");
        }
        final Path outputPath = paths.length > 1 ? new Path(paths[1].toUri() + "-" + input.getName()) : null;

        if (closeness >= 0) {
            // Get query points according to its closeness to grid intersections
            GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile);
            long seed = params.getLong("seed", System.currentTimeMillis());
            Random random = new Random(seed);
            for (int i = 0; i < count; i++) {
                int i_block = random.nextInt(gindex.size());
                int direction = random.nextInt(4);
                // Generate a point in the given direction
                // Get center point (x, y)
                Iterator<Partition> iterator = gindex.iterator();
                while (i_block-- >= 0)
                    iterator.next();
                Partition partition = iterator.next();
                double cx = (partition.x1 + partition.x2) / 2;
                double cy = (partition.y1 + partition.y2) / 2;
                double cw = partition.x2 - partition.x1;
                double ch = partition.y2 - partition.y1;
                int signx = ((direction & 1) == 0) ? 1 : -1;
                int signy = ((direction & 2) == 1) ? 1 : -1;
                double x = cx + cw * closeness / 2 * signx;
                double y = cy + ch * closeness / 2 * signy;
                queryPoints[i] = new Point(x, y);
            }
        }

        final BooleanWritable exceptionHappened = new BooleanWritable();

        Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread th, Throwable ex) {
                ex.printStackTrace();
                exceptionHappened.set(true);
            }
        };

        // Run each query in a separate thread
        final Vector<Thread> threads = new Vector<Thread>();
        for (int i = 0; i < queryPoints.length; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {
                        Point query_point = queryPoints[threads.indexOf(this)];
                        OperationsParams newParams = new OperationsParams(params);
                        OperationsParams.setShape(newParams, "point", query_point);
                        Job job = knn(inputFile, outputPath, params);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.setUncaughtExceptionHandler(h);
            threads.add(thread);
        }

        long t1 = System.currentTimeMillis();
        do {
            // Ensure that there is at least MaxConcurrentThreads running
            int i = 0;
            while (i < concurrency && i < threads.size()) {
                Thread.State state = threads.elementAt(i).getState();
                if (state == Thread.State.TERMINATED) {
                    // Thread already terminated, remove from the queue
                    threads.remove(i);
                } else if (state == Thread.State.NEW) {
                    // Start the thread and move to next one
                    threads.elementAt(i++).start();
                } else {
                    // Thread is still running, skip over it
                    i++;
                }
            }
            if (!threads.isEmpty()) {
                try {
                    // Sleep for 10 seconds or until the first thread terminates
                    threads.firstElement().join(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (!threads.isEmpty());
        long t2 = System.currentTimeMillis();
        if (exceptionHappened.get())
            throw new RuntimeException("Not all jobs finished correctly");

        System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis");
        System.out.println("Total iterations: " + TotalIterations);
    }
}

From source file:Main.java

public static ThreadFactory getThreadFactory(final String name, final UncaughtExceptionHandler handler) {
    return new ThreadFactory() {
        @Override/*from w  w  w  .  j a va2 s  . co m*/
        public Thread newThread(Runnable r) {
            Thread t = new Thread(null, r, name, 1024 * 1024);
            t.setDaemon(true);
            t.setUncaughtExceptionHandler(handler);
            return t;
        }
    };
}

From source file:com.cueup.hegemon.TestUtils.java

public static void runConcurrent(int count, Runnable r) throws InterruptedException {
    List<Thread> threads = Lists.newArrayList();
    ErrorCollector errorCollector = new ErrorCollector();

    for (int i = 0; i < count; i++) {
        Thread t = new Thread(r);
        t.setName("testThread" + i);
        t.setUncaughtExceptionHandler(errorCollector);
        threads.add(t);/*ww w.  ja  v a2s.c om*/

    }

    for (Thread t : threads) {
        t.start();
    }

    for (Thread t : threads) {
        t.join();
    }

    errorCollector.assertNoErrors();
}

From source file:net.geoprism.gis.geoserver.GeoserverInitializer.java

public static void setup() {
    GeoserverInitializer init = new GeoserverInitializer();

    try {//from w ww. j av a 2s . c  o  m
        initLog.debug("Attempting to initialize context.");

        // create another thread to avoid blocking the one starting the webapps.
        Thread t = new Thread(new CheckThread());
        t.setUncaughtExceptionHandler(init);
        t.setDaemon(true);
        t.start();

        initLog.debug("Context initialized...[" + GeoserverInitializer.class + "] started.");
    } catch (Throwable t) {
        initLog.error("Could not initialize context.", t);
    }

    // Start the mapping database view cleanup thread
    Thread t = new Thread(cleanup);
    t.setUncaughtExceptionHandler(init);
    t.setDaemon(true);
    t.start();

    // scheduler.scheduleWithFixedDelay(new CleanupRunnable(), 1, 5, TimeUnit.MINUTES);
}

From source file:Main.java

/**
 * Utility method that sets name, daemon status and starts passed thread.
 * @param t thread to frob//w  ww .j  a  v a  2 s . c o m
 * @param name new name
 * @param handler A handler to set on the thread.  Pass null if want to
 * use default handler.
 * @return Returns the passed Thread <code>t</code>.
 */
public static Thread setDaemonThreadRunning(final Thread t, final String name,
        final UncaughtExceptionHandler handler) {
    t.setName(name);
    if (handler != null) {
        t.setUncaughtExceptionHandler(handler);
    }
    t.setDaemon(true);
    t.start();
    return t;
}

From source file:com.ery.estorm.util.Threads.java

/**
 * Get a named {@link ThreadFactory} that just builds daemon threads.
 * /*from ww  w .ja v  a  2 s  .com*/
 * @param prefix
 *            name prefix for all threads created from the factory
 * @param handler
 *            unhandles exception handler to set for all threads
 * @return a thread factory that creates named, daemon threads with the supplied exception handler and normal priority
 */
public static ThreadFactory newDaemonThreadFactory(final String prefix,
        final UncaughtExceptionHandler handler) {
    final ThreadFactory namedFactory = getNamedThreadFactory(prefix);
    return new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = namedFactory.newThread(r);
            if (handler != null) {
                t.setUncaughtExceptionHandler(handler);
            }
            if (!t.isDaemon()) {
                t.setDaemon(true);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }

    };
}

From source file:com.igormaznitsa.sciareto.ui.UiUtils.java

public static void openInSystemViewer(@Nonnull final File file) {
    final Runnable startEdit = new Runnable() {
        @Override// ww w .  j av a2  s  .  co m
        public void run() {
            boolean ok = false;
            if (Desktop.isDesktopSupported()) {
                final Desktop dsk = Desktop.getDesktop();
                if (dsk.isSupported(Desktop.Action.OPEN)) {
                    try {
                        dsk.open(file);
                        ok = true;
                    } catch (Throwable ex) {
                        LOGGER.error("Can't open file in system viewer : " + file, ex);//NOI18N
                    }
                }
            }
            if (!ok) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        DialogProviderManager.getInstance().getDialogProvider()
                                .msgError("Can't open file in system viewer! See the log!");//NOI18N
                        Toolkit.getDefaultToolkit().beep();
                    }
                });
            }
        }
    };
    final Thread thr = new Thread(startEdit, " MMDStartFileEdit");//NOI18N
    thr.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread t, final Throwable e) {
            LOGGER.error("Detected uncaught exception in openInSystemViewer() for file " + file, e);
        }
    });

    thr.setDaemon(true);
    thr.start();
}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Method used to run a multi-threaded benchmark.
 *
 * @param method to measure//from   w  w  w.  ja  va  2 s. c  o  m
 * @param path path to store benchmarking test data
 * @param iterations number of iterations to run
 * @param concurrency number of threads to run
 * @throws IOException thrown when we can't communicate with the server
 */
private static void multithreadedBenchmark(final String method, final String path, final int iterations,
        final int concurrency) throws IOException {
    final AtomicLong fullAggregation = new AtomicLong(0L);
    final AtomicLong serverAggregation = new AtomicLong(0L);
    final AtomicLong count = new AtomicLong(0L);
    final long perThreadCount = perThreadCount(iterations, concurrency);

    System.out.printf("Running %d iterations per thread\n", perThreadCount);

    final long testStart = System.nanoTime();

    Runtime.getRuntime().addShutdownHook(new Thread(Benchmark::cleanUp));

    final Callable<Void> worker = () -> {
        for (int i = 0; i < perThreadCount; i++) {
            Duration[] durations;

            if (method.equals("put")) {
                durations = measurePut(sizeInBytesOrNoOfDirs);
            } else if (method.equals("putDir")) {
                durations = measurePutDir(sizeInBytesOrNoOfDirs);
            } else {
                durations = measureGet(path);
            }

            long fullLatency = durations[0].toMillis();
            long serverLatency = durations[1].toMillis();
            fullAggregation.addAndGet(fullLatency);
            serverAggregation.addAndGet(serverLatency);

            System.out.printf("%s %d full=%dms, server=%dms, thread=%s\n", method, count.getAndIncrement(),
                    fullLatency, serverLatency, Thread.currentThread().getName());
        }

        return null;
    };

    final Thread.UncaughtExceptionHandler handler = (t, e) -> LOG.error("Error when executing benchmark", e);

    final AtomicInteger threadCounter = new AtomicInteger(0);
    ThreadFactory threadFactory = r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        t.setUncaughtExceptionHandler(handler);
        t.setName(String.format("benchmark-%d", threadCounter.incrementAndGet()));

        return t;
    };

    ExecutorService executor = Executors.newFixedThreadPool(concurrency, threadFactory);

    List<Callable<Void>> workers = new ArrayList<>(concurrency);
    for (int i = 0; i < concurrency; i++) {
        workers.add(worker);
    }

    try {
        List<Future<Void>> futures = executor.invokeAll(workers);

        boolean completed = false;
        while (!completed) {
            try (Stream<Future<Void>> stream = futures.stream()) {
                completed = stream.allMatch((f) -> f.isDone() || f.isCancelled());

                if (!completed) {
                    Thread.sleep(CHECK_INTERVAL);
                }
            }
        }

    } catch (InterruptedException e) {
        return;
    } finally {
        System.err.println("Shutting down the thread pool");
        executor.shutdown();
    }

    final long testEnd = System.nanoTime();

    final long fullAverage = Math.round(fullAggregation.get() / iterations);
    final long serverAverage = Math.round(serverAggregation.get() / iterations);
    final long totalTime = Duration.ofNanos(testEnd - testStart).toMillis();

    System.out.printf("Average full latency: %d ms\n", fullAverage);
    System.out.printf("Average server latency: %d ms\n", serverAverage);
    System.out.printf("Total test time: %d ms\n", totalTime);
    System.out.printf("Total invocations: %d\n", count.get());
}

From source file:com.igormaznitsa.ideamindmap.utils.IdeaUtils.java

public static void openInSystemViewer(@Nonnull final DialogProvider dialogProvider,
        @Nullable final VirtualFile theFile) {
    final File file = vfile2iofile(theFile);

    if (file == null) {
        LOGGER.error("Can't find file to open, null provided");
        dialogProvider.msgError("Can't find file to open");
    } else {//from  w  ww  .  ja  v  a2s .c o m
        final Runnable startEdit = new Runnable() {
            @Override
            public void run() {
                boolean ok = false;
                if (Desktop.isDesktopSupported()) {
                    final Desktop dsk = Desktop.getDesktop();
                    if (dsk.isSupported(Desktop.Action.OPEN)) {
                        try {
                            dsk.open(file);
                            ok = true;
                        } catch (Throwable ex) {
                            LOGGER.error("Can't open file in system viewer : " + file, ex);//NOI18N
                        }
                    }
                }
                if (!ok) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialogProvider.msgError("Can't open file in system viewer! See the log!");//NOI18N
                            Toolkit.getDefaultToolkit().beep();
                        }
                    });
                }
            }
        };
        final Thread thr = new Thread(startEdit, " MMDStartFileEdit");//NOI18N
        thr.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(final Thread t, final Throwable e) {
                LOGGER.error("Detected uncaught exception in openInSystemViewer() for file " + file, e);
            }
        });

        thr.setDaemon(true);
        thr.start();
    }
}

From source file:com.apptentive.android.sdk.module.engagement.interaction.InteractionManager.java

public static void asyncFetchAndStoreInteractions(final Context context) {

    if (!isPollForInteractions(context)) {
        Log.v("Interaction polling is disabled.");
        return;//from  w w w.  j  ava  2s.  c om
    }

    if (hasCacheExpired(context)) {
        Log.d("Interaction cache has expired. Fetching new interactions.");
        Thread thread = new Thread() {
            public void run() {
                fetchAndStoreInteractions(context);
            }
        };
        Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                Log.w("UncaughtException in InteractionManager.", throwable);
                MetricModule.sendError(context.getApplicationContext(), throwable, null, null);
            }
        };
        thread.setUncaughtExceptionHandler(handler);
        thread.setName("Apptentive-FetchInteractions");
        thread.start();
    } else {
        Log.d("Interaction cache has not expired. Using existing interactions.");
    }
}