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:Uncaught.java

public static void main(String[] args) {
    Thread thread = new Thread(new Uncaught());
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();/*ww w  . j  ava  2  s  .  c o  m*/
        }
    });
    thread.start();
}

From source file:MainClass.java

public static void main(String[] args) {
    Thread thread = new Thread(new MyThread());
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println(t + " threw exception: " + e);
        }//from   w w  w  .  ja  v a 2  s .  c  o  m
    });
    thread.start();
}

From source file:Main.java

public static void main(String[] args) {
    Thread t = new Thread(new Main());
    t.setUncaughtExceptionHandler(new OverrideExceptionHandler());
    System.out.println(t.getUncaughtExceptionHandler());
    t.start();/*w  ww  .  j  a  v  a2  s  .co m*/
}

From source file:Main.java

public static void main(String[] args) {

    Thread t = new Thread(new MyThread());
    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        public void uncaughtException(Thread t, Throwable e) {
            System.out.println(t + " throws exception: " + e);
        }//from  w w w  . ja va  2 s  . co m
    });
    t.start();
}

From source file:TestOverrideThread.java

public static void main(String[] args) {
    Thread t = new Thread(new TestOverrideThread());
    t.setUncaughtExceptionHandler(new OverrideExceptionHandler());
    System.out.println(t.getUncaughtExceptionHandler());
    t.start();//from   ww w . j a  v a2s . c  o  m
}

From source file:Main.java

public static void main(String[] args) {
    Thread thread = new Thread() {
        public void run() {
            throw new NullPointerException();
        }/*from   www .  j  ava  2 s . c  om*/
    };
    thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread arg0, Throwable arg1) {
            arg1.printStackTrace();
        }
    });
    thread.start();
}

From source file:com.github.ambry.store.DiskReformatter.java

public static void main(String[] args) throws Exception {
    VerifiableProperties properties = ToolUtils.getVerifiableProperties(args);
    DiskReformatterConfig config = new DiskReformatterConfig(properties);
    StoreConfig storeConfig = new StoreConfig(properties);
    ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties);
    ServerConfig serverConfig = new ServerConfig(properties);
    ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory,
            clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath);
    try (ClusterMap clusterMap = clusterAgentsFactory.getClusterMap()) {
        StoreKeyConverterFactory storeKeyConverterFactory = Utils.getObj(
                serverConfig.serverStoreKeyConverterFactory, properties, clusterMap.getMetricRegistry());
        StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap);
        DataNodeId dataNodeId = clusterMap.getDataNodeId(config.datanodeHostname, config.datanodePort);
        if (dataNodeId == null) {
            throw new IllegalArgumentException("Did not find node in clustermap with hostname:port - "
                    + config.datanodeHostname + ":" + config.datanodePort);
        }//from w w  w .j a  v  a2 s  .  co m
        DiskReformatter reformatter = new DiskReformatter(dataNodeId, Collections.EMPTY_LIST,
                config.fetchSizeInBytes, storeConfig, storeKeyFactory, clusterMap, SystemTime.getInstance(),
                storeKeyConverterFactory.getStoreKeyConverter());
        AtomicInteger exitStatus = new AtomicInteger(0);
        CountDownLatch latch = new CountDownLatch(config.diskMountPaths.length);
        for (int i = 0; i < config.diskMountPaths.length; i++) {
            int finalI = i;
            Runnable runnable = () -> {
                try {
                    reformatter.reformat(config.diskMountPaths[finalI], new File(config.scratchPaths[finalI]));
                    latch.countDown();
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            };
            Thread thread = Utils.newThread(config.diskMountPaths[finalI] + "-reformatter", runnable, true);
            thread.setUncaughtExceptionHandler((t, e) -> {
                exitStatus.set(1);
                logger.error("Reformatting {} failed", config.diskMountPaths[finalI], e);
                latch.countDown();
            });
            thread.start();
        }
        latch.await();
        System.exit(exitStatus.get());
    }
}

From source file:com.ricemap.spateDB.operations.RangeQuery.java

public static void main(String[] args) throws IOException {
    CommandLineArguments cla = new CommandLineArguments(args);
    final QueryInput query = cla.getQuery();
    final Path[] paths = cla.getPaths();
    if (paths.length == 0 || (cla.getPrism() == null && cla.getSelectionRatio() < 0.0f)) {
        printUsage();/*from  w  w w. ja  v a2 s  .c  o  m*/
        throw new RuntimeException("Illegal parameters");
    }
    JobConf conf = new JobConf(FileMBR.class);
    final Path inputFile = paths[0];
    final FileSystem fs = inputFile.getFileSystem(conf);
    if (!fs.exists(inputFile)) {
        printUsage();
        throw new RuntimeException("Input file does not exist");
    }
    final Path outputPath = paths.length > 1 ? paths[1] : null;
    final Prism[] queryRanges = cla.getPrisms();
    int concurrency = cla.getConcurrency();
    final Shape stockShape = cla.getShape(true);
    final boolean overwrite = cla.isOverwrite();

    final long[] results = new long[queryRanges.length];
    final Vector<Thread> threads = new Vector<Thread>();

    final BooleanWritable exceptionHappened = new BooleanWritable();

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

    for (int i = 0; i < queryRanges.length; i++) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    int thread_i = threads.indexOf(this);

                    long result_count = rangeQueryMapReduce(fs, inputFile, outputPath, queryRanges[thread_i],
                            stockShape, overwrite, false, query);
                    results[thread_i] = result_count;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        t.setUncaughtExceptionHandler(h);
        threads.add(t);
    }

    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 " + queryRanges.length + " jobs is " + (t2 - t1) + " millis");

    System.out.print("Result size: [");
    for (long result : results) {
        System.out.print(result + ", ");
    }
    System.out.println("]");
}

From source file:edu.umn.cs.spatialHadoop.operations.KNN.java

public static void main(String[] args) throws IOException {
    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();/*from  w w  w .  ja va 2 s. c o  m*/
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }
    final Path inputFile = params.getInputPath();
    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 ? paths[1] : 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:edu.umn.cs.sthadoop.trajectory.KNNDTW.java

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

    args = new String[10];
    args[0] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/index_geolife/yyyy-MM/2008-05";
    args[1] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/knn-dis-result";
    args[2] = "shape:edu.umn.cs.sthadoop.trajectory.GeolifeTrajectory";
    args[3] = "interval:2008-05-01,2008-05-30";
    args[4] = "time:month";
    args[5] = "k:1";
    args[6] = "traj:39.9119983,116.606835;39.9119783,116.6065483;39.9119599,116.6062649;39.9119416,116.6059899;39.9119233,116.6057282;39.9118999,116.6054783;39.9118849,116.6052366;39.9118666,116.6050099;39.91185,116.604775;39.9118299,116.604525;39.9118049,116.6042649;39.91177,116.6040166;39.9117516,116.6037583;39.9117349,116.6035066;39.9117199,116.6032666;39.9117083,116.6030232;39.9117,116.6027566;39.91128,116.5969383;39.9112583,116.5966766;39.9112383,116.5964232;39.9112149,116.5961699;39.9111933,116.5959249;39.9111716,116.5956883";
    args[7] = "-overwrite";
    args[8] = "-local";// "-no-local";
    args[9] = "point:39.9119983,116.606835";

    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();//  w  ww .j a va  2s  . co m
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }
    final Path inputFile = params.getInputPath();
    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 ? paths[1] : 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);
}