Example usage for java.lang Thread setDefaultUncaughtExceptionHandler

List of usage examples for java.lang Thread setDefaultUncaughtExceptionHandler

Introduction

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

Prototype

public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) 

Source Link

Document

Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.

Usage

From source file:brainflow.app.toplevel.BrainFlow.java

private void initExceptionHandler() {
    LookAndFeelFactory.UIDefaultsCustomizer uiDefaultsCustomizer = new LookAndFeelFactory.UIDefaultsCustomizer() {
        public void customize(UIDefaults defaults) {
            ThemePainter painter = (ThemePainter) UIDefaultsLookup.get("Theme.painter");
            defaults.put("OptionPaneUI", "com.jidesoft.plaf.basic.BasicJideOptionPaneUI");

            defaults.put("OptionPane.showBanner", Boolean.TRUE); // show banner or not. default is true
            //defaults.put("OptionPane.bannerIcon", JideIconsFactory.getImageIcon(JideIconsFactory.JIDE50));
            defaults.put("OptionPane.bannerFontSize", 13);
            defaults.put("OptionPane.bannerFontStyle", Font.BOLD);
            defaults.put("OptionPane.bannerMaxCharsPerLine", 60);
            defaults.put("OptionPane.bannerForeground",
                    painter != null ? painter.getOptionPaneBannerForeground() : null); // you should adjust this if banner background is not the default gradient paint
            defaults.put("OptionPane.bannerBorder", null); // use default border

            // set both bannerBackgroundDk and // set both bannerBackgroundLt to null if you don't want gradient
            defaults.put("OptionPane.bannerBackgroundDk",
                    painter != null ? painter.getOptionPaneBannerDk() : null);
            defaults.put("OptionPane.bannerBackgroundLt",
                    painter != null ? painter.getOptionPaneBannerLt() : null);
            defaults.put("OptionPane.bannerBackgroundDirection", Boolean.TRUE); // default is true

            // optionally, you can set a Paint object for BannerPanel. If so, the three UIDefaults related to banner background above will be ignored.
            defaults.put("OptionPane.bannerBackgroundPaint", null);

            defaults.put("OptionPane.buttonAreaBorder", BorderFactory.createEmptyBorder(6, 6, 6, 6));
            defaults.put("OptionPane.buttonOrientation", SwingConstants.RIGHT);
        }/*w ww  . j  a v a 2  s.co  m*/
    };
    uiDefaultsCustomizer.customize(UIManager.getDefaults());

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            ExceptionDialog ed = new ExceptionDialog(e);
            JDialog dialog = ed.createDialog(brainFrame);
            dialog.setVisible(true);
        }
    });

}

From source file:org.apache.hadoop.mapreduce.v2.app.MRAppMaster.java

public static void main(String[] args) {
    try {/*  w ww . j av  a 2s  .c o m*/
        mainStarted = true;
        Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler());
        String containerIdStr = System.getenv(Environment.CONTAINER_ID.name());
        String nodeHostString = System.getenv(Environment.NM_HOST.name());
        String nodePortString = System.getenv(Environment.NM_PORT.name());
        String nodeHttpPortString = System.getenv(Environment.NM_HTTP_PORT.name());
        String appSubmitTimeStr = System.getenv(ApplicationConstants.APP_SUBMIT_TIME_ENV);

        validateInputParam(containerIdStr, Environment.CONTAINER_ID.name());
        validateInputParam(nodeHostString, Environment.NM_HOST.name());
        validateInputParam(nodePortString, Environment.NM_PORT.name());
        validateInputParam(nodeHttpPortString, Environment.NM_HTTP_PORT.name());
        validateInputParam(appSubmitTimeStr, ApplicationConstants.APP_SUBMIT_TIME_ENV);

        ContainerId containerId = ContainerId.fromString(containerIdStr);
        ApplicationAttemptId applicationAttemptId = containerId.getApplicationAttemptId();
        if (applicationAttemptId != null) {
            CallerContext.setCurrent(
                    new CallerContext.Builder("mr_appmaster_" + applicationAttemptId.toString()).build());
        }
        long appSubmitTime = Long.parseLong(appSubmitTimeStr);

        MRAppMaster appMaster = new MRAppMaster(applicationAttemptId, containerId, nodeHostString,
                Integer.parseInt(nodePortString), Integer.parseInt(nodeHttpPortString), appSubmitTime);
        ShutdownHookManager.get().addShutdownHook(new MRAppMasterShutdownHook(appMaster),
                SHUTDOWN_HOOK_PRIORITY);
        JobConf conf = new JobConf(new YarnConfiguration());
        conf.addResource(new Path(MRJobConfig.JOB_CONF_FILE));

        MRWebAppUtil.initialize(conf);
        // log the system properties
        String systemPropsToLog = MRApps.getSystemPropertiesToLog(conf);
        if (systemPropsToLog != null) {
            LOG.info(systemPropsToLog);
        }

        String jobUserName = System.getenv(ApplicationConstants.Environment.USER.name());
        conf.set(MRJobConfig.USER_NAME, jobUserName);
        initAndStartAppMaster(appMaster, conf, jobUserName);
    } catch (Throwable t) {
        LOG.fatal("Error starting MRAppMaster", t);
        ExitUtil.terminate(1, t);
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.ResourceManager.java

public static void main(String argv[]) {
    Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler());
    StringUtils.startupShutdownMessage(ResourceManager.class, argv, LOG);
    try {//from   www .j  av  a  2 s.  co  m
        Configuration conf = new YarnConfiguration();
        YarnAPIStorageFactory.setConfiguration(conf);
        RMStorageFactory.setConfiguration(conf);
        GenericOptionsParser hParser = new GenericOptionsParser(conf, argv);
        argv = hParser.getRemainingArgs();
        // If -format-state-store, then delete RMStateStore; else startup normally
        if (argv.length >= 1) {
            if (argv[0].equals("-format-state-store")) {
                deleteRMStateStore(conf);
            } else if (argv[0].equals("-remove-application-from-state-store") && argv.length == 2) {
                removeApplication(conf, argv[1]);
            } else {
                printUsage(System.err);
            }
        } else {
            ResourceManager resourceManager = new ResourceManager();
            ShutdownHookManager.get().addShutdownHook(new CompositeServiceShutdownHook(resourceManager),
                    SHUTDOWN_HOOK_PRIORITY);
            resourceManager.init(conf);
            resourceManager.start();
        }
    } catch (Throwable t) {
        LOG.fatal("Error starting ResourceManager", t);
        System.exit(-1);
    }
}

From source file:org.archiviststoolkit.mydomain.DomainTableWorkSurface.java

public void exportMARC() {
    final int[] selectedIndexes = table.getSelectedRows();
    final ExportOptionsMARC exportOptions = new ExportOptionsMARC();
    final File selectedFileOrDirectory = FileUtils.chooseFileOrDirectory(selectedIndexes.length, exportOptions);

    if (selectedFileOrDirectory != null) {
        Thread performer = new Thread(new Runnable() {
            public void run() {
                // see whether to show the cancel button
                boolean allowCancel = false;
                if (selectedIndexes.length > 1) {
                    allowCancel = true;// w w w .  java 2  s.  c  o  m
                }

                InfiniteProgressPanel monitor = ATProgressUtil
                        .createModalProgressMonitor(ApplicationFrame.getInstance(), 1000, allowCancel);
                monitor.start("Exporting...");
                MARCExportHandler batchMARCHandler = new MARCExportHandler(exportOptions);
                try {
                    int[] selectedIndexes = table.getSelectedRows();
                    Vector<DomainObject> resources = new Vector<DomainObject>();
                    DomainObject domainObject = null;
                    DomainObject fullDomainObject = null;

                    for (int loop = 0; loop < selectedIndexes.length; loop++) {
                        // check to see if this operation wasnt cancelled
                        if (monitor.isProcessCancelled()) {
                            break;
                        }

                        domainObject = (table.getFilteredList().get(selectedIndexes[loop]));
                        resources.add(domainObject);
                    }

                    if (!monitor.isProcessCancelled()) {
                        Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
                        batchMARCHandler.export(selectedFileOrDirectory, resources, monitor);
                    }
                } catch (Exception e) {
                    monitor.close();
                    new ErrorDialog("", e).showDialog();
                } finally {
                    monitor.close();
                }
            }
        }, "ExportMarc");
        performer.start();
    }

}

From source file:github.popeen.dsub.activity.SubsonicActivity.java

private void setUncaughtExceptionHandler() {
    Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
    if (!(handler instanceof SubsonicActivity.SubsonicUncaughtExceptionHandler)) {
        Thread.setDefaultUncaughtExceptionHandler(new SubsonicActivity.SubsonicUncaughtExceptionHandler(this));
    }//w  w  w. ja  v a 2 s  . com
}

From source file:org.archiviststoolkit.mydomain.DomainTableWorkSurface.java

public void exportEAD() {
    final int[] selectedIndexes = table.getSelectedRows();
    final ExportOptionsEAD exportOptions = new ExportOptionsEAD();
    final File selectedFileOrDirectory = FileUtils.chooseFileOrDirectory(selectedIndexes.length, exportOptions);

    if (selectedFileOrDirectory != null) {
        Thread performer = new Thread(new Runnable() {
            public void run() {
                // see whether to show the cancel button
                boolean allowCancel = false;
                if (selectedIndexes.length > 1) {
                    allowCancel = true;//from   ww w.  j a v a  2  s.  c  o  m
                }

                InfiniteProgressPanel monitor = ATProgressUtil
                        .createModalProgressMonitor(ApplicationFrame.getInstance(), 1000, allowCancel);
                monitor.start("Exporting...");
                EADExportHandler batchEADHandler = new EADExportHandler(exportOptions);

                try {
                    Vector<DomainObject> resources = new Vector<DomainObject>();
                    DomainObject domainObject = null;
                    DomainObject fullDomainObject = null;

                    for (int loop = 0; loop < selectedIndexes.length; loop++) {
                        // check to see if this operation wasnt cancelled
                        if (monitor.isProcessCancelled()) {
                            break;
                        }

                        access = new ResourcesDAO();
                        domainObject = (table.getFilteredList().get(selectedIndexes[loop]));
                        //try {
                        fullDomainObject = access.findByPrimaryKeyLongSession(domainObject.getIdentifier());
                        //}
                        //catch (LookupException le) {
                        //monitor.close();
                        ///new ErrorDialog(ApplicationFrame.getInstance(), "", le).showDialog();
                        //}
                        resources.add(fullDomainObject);
                        //resources.add(domainObject);
                    }

                    if (!monitor.isProcessCancelled()) {
                        Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
                        batchEADHandler.export(selectedFileOrDirectory, resources, monitor);
                    }
                } catch (Exception e) {
                    monitor.close();
                    new ErrorDialog("", e).showDialog();
                } finally {
                    monitor.close();
                }
            }
        }, "ExportEAD");
        performer.start();
    }

}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * Creates and attaches the UnhandledException handler for piping them to the dialog
 *//*from ww  w.  j  a va 2s.  c  o m*/
public static void attachUnhandledException() {
    log.debug("attachUnhandledException " + Thread.currentThread().getName() + " "
            + Thread.currentThread().hashCode());

    Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            if (isExceptionOKToThrow(e)) {
                mailUnhandledException(e);

                UIHelper.showUnhandledException(e);
            }
            UsageTracker.incrUsageCount("UncaughtException");
            e.printStackTrace();
        }
    });

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            if (isExceptionOKToThrow(e)) {
                mailUnhandledException(e);

                UIHelper.showUnhandledException(e);
            }
            UsageTracker.incrUsageCount("UncaughtException");
            e.printStackTrace();
        }
    });
}

From source file:com.androzic.Androzic.java

public void onCreateEx() {
    try {//from  w  w w .  j a  v a 2  s  .  co  m
        (new File(Environment.getExternalStorageDirectory(), WordManager.FOLDER)).mkdirs();
        (new File(Environment.getExternalStorageDirectory(), WordManager.FOLDER + "/ghiam")).mkdirs();
    } catch (Throwable e) {
    }

    if (initialized)
        return;

    AndroidGraphicFactory.createInstance(this);
    try {
        OzfDecoder.useNativeCalls();
    } catch (UnsatisfiedLinkError e) {
        Toast.makeText(Androzic.this, "Failed to initialize native library: " + e.getMessage(),
                Toast.LENGTH_LONG).show();
    }

    Resources resources = getResources();
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    Configuration config = resources.getConfiguration();

    renderingThread = new HandlerThread("RenderingThread");
    renderingThread.start();

    longOperationsThread = new HandlerThread("LongOperationsThread");
    longOperationsThread.setPriority(Thread.MIN_PRIORITY);
    longOperationsThread.start();

    uiHandler = new Handler();
    mapsHandler = new Handler(longOperationsThread.getLooper());

    // We silently initialize data uri to let location service restart after crash
    File datadir = new File(
            settings.getString(getString(R.string.pref_folder_data), Environment.getExternalStorageDirectory()
                    + File.separator + resources.getString(R.string.def_folder_data)));
    setDataPath(Androzic.PATH_DATA, datadir.getAbsolutePath());

    setInstance(this);

    String intentToCheck = "com.androzic.donate";
    String myPackageName = getPackageName();
    PackageManager pm = getPackageManager();
    PackageInfo pi;
    try {
        pi = pm.getPackageInfo(intentToCheck, 0);
        isPaid = (pm.checkSignatures(myPackageName, pi.packageName) == PackageManager.SIGNATURE_MATCH);
    } catch (NameNotFoundException e) {
        //         e.printStackTrace();
    }

    File sdcard = Environment.getExternalStorageDirectory();
    Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(this, sdcard.getAbsolutePath()));

    DisplayMetrics displayMetrics = new DisplayMetrics();

    WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    if (wm != null) {
        wm.getDefaultDisplay().getMetrics(displayMetrics);
    } else {
        displayMetrics.setTo(resources.getDisplayMetrics());
    }
    BaseMap.viewportWidth = displayMetrics.widthPixels;
    BaseMap.viewportHeight = displayMetrics.heightPixels;

    charset = settings.getString(getString(R.string.pref_charset), "UTF-8");
    String lang = settings.getString(getString(R.string.pref_locale), "");
    if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {
        locale = new Locale(lang);
        Locale.setDefault(locale);
        config.locale = locale;
        resources.updateConfiguration(config, resources.getDisplayMetrics());
    }

    magInterval = resources.getInteger(R.integer.def_maginterval) * 1000;

    overlayManager = new OverlayManager(longOperationsThread.getLooper());
    TooltipManager.initialize(this);

    onSharedPreferenceChanged(settings, getString(R.string.pref_unitcoordinate));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitdistance));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitspeed));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitelevation));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitangle));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitanglemagnetic));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitprecision));
    onSharedPreferenceChanged(settings, getString(R.string.pref_unitsunrise));
    onSharedPreferenceChanged(settings, getString(R.string.pref_mapadjacent));
    onSharedPreferenceChanged(settings, getString(R.string.pref_vectormap_textscale));
    onSharedPreferenceChanged(settings, getString(R.string.pref_onlinemapprescalefactor));
    onSharedPreferenceChanged(settings, getString(R.string.pref_onlinemapexpiration));
    onSharedPreferenceChanged(settings, getString(R.string.pref_mapcropborder));
    onSharedPreferenceChanged(settings, getString(R.string.pref_mapdrawborder));
    onSharedPreferenceChanged(settings, getString(R.string.pref_showwaypoints));
    onSharedPreferenceChanged(settings, getString(R.string.pref_showcurrenttrack));
    onSharedPreferenceChanged(settings, getString(R.string.pref_showaccuracy));
    onSharedPreferenceChanged(settings, getString(R.string.pref_showdistance_int));

    settings.registerOnSharedPreferenceChangeListener(this);

    initialized = true;
}

From source file:org.neo4j.io.pagecache.PageCacheTest.java

@Test(timeout = SEMI_LONG_TIMEOUT_MILLIS)
public void backgroundThreadsMustGracefullyShutDown() throws Exception {
    assumeTrue("For some reason, this test is very flaky on Windows", !SystemUtils.IS_OS_WINDOWS);

    int iterations = 1000;
    List<WeakReference<PageCache>> refs = new LinkedList<>();
    final Queue<Throwable> caughtExceptions = new ConcurrentLinkedQueue<>();
    final Thread.UncaughtExceptionHandler exceptionHandler = (t, e) -> {
        e.printStackTrace();//from w  ww  .j a va  2  s .c  o  m
        caughtExceptions.offer(e);
    };
    Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread
            .getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

    try {
        generateFileWithRecords(file("a"), recordCount, recordSize);
        int filePagesInTotal = recordCount / recordsPerFilePage;

        for (int i = 0; i < iterations; i++) {
            PageCache cache = createPageCache(fs, maxPages, pageCachePageSize, PageCacheTracer.NULL);

            // Touch all the pages
            PagedFile pagedFile = cache.map(file("a"), filePageSize);
            try (PageCursor cursor = pagedFile.io(0, PF_SHARED_READ_LOCK)) {
                for (int j = 0; j < filePagesInTotal; j++) {
                    assertTrue(cursor.next());
                }
            }

            // We're now likely racing with the eviction thread
            pagedFile.close();
            cache.close();
            refs.add(new WeakReference<>(cache));

            assertTrue(caughtExceptions.isEmpty());
        }
    } finally {
        Thread.setDefaultUncaughtExceptionHandler(defaultUncaughtExceptionHandler);
    }

    // Once the page caches has been closed and all references presumably set to null, then the only thing that
    // could possibly strongly reference the cache is any lingering background thread. If we do a couple of
    // GCs, then we should observe that the WeakReference has been cleared by the garbage collector. If it
    // hasn't, then something must be keeping it alive, even though it has been closed.
    int maxChecks = 100;
    boolean passed;
    do {
        System.gc();
        Thread.sleep(100);
        passed = true;

        for (WeakReference<PageCache> ref : refs) {
            if (ref.get() != null) {
                passed = false;
            }
        }
    } while (!passed && maxChecks-- > 0);

    if (!passed) {
        List<PageCache> nonNullPageCaches = new LinkedList<>();
        for (WeakReference<PageCache> ref : refs) {
            PageCache pageCache = ref.get();
            if (pageCache != null) {
                nonNullPageCaches.add(pageCache);
            }
        }

        if (!nonNullPageCaches.isEmpty()) {
            fail("PageCaches should not be held live after close: " + nonNullPageCaches);
        }
    }
}

From source file:pipeline.A0PipeLine_Manager.java

@Override
public void run(String s) {
    Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
    try {// w  w  w .  j  a  v  a  2  s  .  co  m
        addDir(getBaseDir() + "/native_libs/" + DylibInfo.getDylibInfo().directoryName + "/");
    } catch (IOException e) {
        Utils.printStack(e);
    }
    System.setProperty("jna.library.path",
            getBaseDir() + "/native_libs/" + DylibInfo.getDylibInfo().directoryName + "/");

    Utils.setLogFile(A0PipeLine_Manager.getBaseDir() + "/pipeline_log.txt");

    javax.swing.SwingUtilities.invokeLater(() -> {
        table = new TableSelectionDemo();
        // RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());
        table.createAndShowGUI();
    });
}