最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java之Thread不捕獲異常默認(rèn)處理邏輯

 更新時(shí)間:2023年12月11日 15:31:12   作者:QMCoder  
這篇文章主要介紹了java之Thread不捕獲異常默認(rèn)處理邏輯,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

直接new Thread(()->{})默認(rèn)處理邏輯

Thread 類(lèi), 發(fā)生異常未捕獲,默認(rèn)JVM調(diào)用 dispatchUncaughtException 方法

	
    /**
     * Dispatch an uncaught exception to the handler. This method is
     * intended to be called only by the JVM.
     */
    private void dispatchUncaughtException(Throwable e) {
        getUncaughtExceptionHandler().uncaughtException(this, e);
    }

	// 線程實(shí)例的默認(rèn)異常處理, 需要手動(dòng)設(shè)置, 不設(shè)置默認(rèn)為null
    private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
    /**
     * Returns the handler invoked when this thread abruptly terminates
     * due to an uncaught exception. If this thread has not had an
     * uncaught exception handler explicitly set then this thread's
     * <tt>ThreadGroup</tt> object is returned, unless this thread
     * has terminated, in which case <tt>null</tt> is returned.
     * @since 1.5
     * @return the uncaught exception handler for this thread
     */
    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
        return uncaughtExceptionHandler != null ?
            uncaughtExceptionHandler : group;  // group就是線程對(duì)應(yīng)的線程組
    }

什么都不設(shè)置, 默認(rèn)最后回來(lái)到ThreadGroup的uncaughtException 方法

    
    /**
     * Called by the Java Virtual Machine when a thread in this
     * thread group stops because of an uncaught exception, and the thread
     * does not have a specific {@link Thread.UncaughtExceptionHandler}
     * installed.
     * <p>
     * The <code>uncaughtException</code> method of
     * <code>ThreadGroup</code> does the following:
     * <ul>
     * <li>If this thread group has a parent thread group, the
     *     <code>uncaughtException</code> method of that parent is called
     *     with the same two arguments.
     * <li>Otherwise, this method checks to see if there is a
     *     {@linkplain Thread#getDefaultUncaughtExceptionHandler default
     *     uncaught exception handler} installed, and if so, its
     *     <code>uncaughtException</code> method is called with the same
     *     two arguments.
     * <li>Otherwise, this method determines if the <code>Throwable</code>
     *     argument is an instance of {@link ThreadDeath}. If so, nothing
     *     special is done. Otherwise, a message containing the
     *     thread's name, as returned from the thread's {@link
     *     Thread#getName getName} method, and a stack backtrace,
     *     using the <code>Throwable</code>'s {@link
     *     Throwable#printStackTrace printStackTrace} method, is
     *     printed to the {@linkplain System#err standard error stream}.
     * </ul>
     * <p>
     * Applications can override this method in subclasses of
     * <code>ThreadGroup</code> to provide alternative handling of
     * uncaught exceptions.
     *
     * @param   t   the thread that is about to exit.
     * @param   e   the uncaught exception.
     * @since   JDK1.0
     */
    public void uncaughtException(Thread t, Throwable e) {
        if (parent != null) {
            parent.uncaughtException(t, e);
        } else {
            Thread.UncaughtExceptionHandler ueh =
                Thread.getDefaultUncaughtExceptionHandler();  // 全局的異常處理器 Thread靜態(tài)字段, 手動(dòng)設(shè)置, 不設(shè)置默認(rèn)為null
            if (ueh != null) {
                ueh.uncaughtException(t, e);
            } else if (!(e instanceof ThreadDeath)) {
                System.err.print("Exception in thread \""
                                 + t.getName() + "\" ");
                e.printStackTrace(System.err);  // 都不設(shè)置默認(rèn)輸出到 標(biāo)準(zhǔn)錯(cuò)誤輸出
            }
        }
    }

線程池默認(rèn)處理邏輯

ThreadPoolExecutor#runWorker 方法

    
    /**
     * Main worker run loop.  Repeatedly gets tasks from queue and
     * executes them, while coping with a number of issues:
     *
     * 1. We may start out with an initial task, in which case we
     * don't need to get the first one. Otherwise, as long as pool is
     * running, we get tasks from getTask. If it returns null then the
     * worker exits due to changed pool state or configuration
     * parameters.  Other exits result from exception throws in
     * external code, in which case completedAbruptly holds, which
     * usually leads processWorkerExit to replace this thread.
     *
     * 2. Before running any task, the lock is acquired to prevent
     * other pool interrupts while the task is executing, and then we
     * ensure that unless pool is stopping, this thread does not have
     * its interrupt set.
     *
     * 3. Each task run is preceded by a call to beforeExecute, which
     * might throw an exception, in which case we cause thread to die
     * (breaking loop with completedAbruptly true) without processing
     * the task.
     *
     * 4. Assuming beforeExecute completes normally, we run the task,
     * gathering any of its thrown exceptions to send to afterExecute.
     * We separately handle RuntimeException, Error (both of which the
     * specs guarantee that we trap) and arbitrary Throwables.
     * Because we cannot rethrow Throwables within Runnable.run, we
     * wrap them within Errors on the way out (to the thread's
     * UncaughtExceptionHandler).  Any thrown exception also
     * conservatively causes thread to die.
     *
     * 5. After task.run completes, we call afterExecute, which may
     * also throw an exception, which will also cause thread to
     * die. According to JLS Sec 14.20, this exception is the one that
     * will be in effect even if task.run throws.
     *
     * The net effect of the exception mechanics is that afterExecute
     * and the thread's UncaughtExceptionHandler have as accurate
     * information as we can provide about any problems encountered by
     * user code.
     *
     * @param w the worker
     */
    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                w.lock();
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run(); 
                    } catch (RuntimeException x) {
                        thrown = x; throw x;    // 發(fā)生異常直接拋出, 最后也會(huì)走到Thread的異常處理邏輯
                    } catch (Error x) {
                        thrown = x; throw x;  // 發(fā)生異常直接拋出 最后也會(huì)走到Thread的異常處理邏輯
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x); // 發(fā)生異常拋出 最后也會(huì)走到Thread的異常處理邏輯
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);  // 發(fā)生異常whiie循環(huán)結(jié)束  當(dāng)前線程退出處理  
        }
    }

線程池的 execute 和 submit 方法異常處理 異同

    /**
     * @throws RejectedExecutionException {@inheritDoc}
     * @throws NullPointerException       {@inheritDoc}
     */
    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);  // 任務(wù)被包裝成FutureTask, FutureTask的run方法處理了異常, 所以如果默認(rèn)task不處理異常,需要調(diào)用futureTask.get()方法獲取結(jié)果或者異常,否則表象就是異常吞掉了
        execute(ftask);
        return ftask;
    }
    /**
     * Returns a {@code RunnableFuture} for the given callable task.
     *
     * @param callable the callable task being wrapped
     * @param <T> the type of the callable's result
     * @return a {@code RunnableFuture} which, when run, will call the
     * underlying callable and which, as a {@code Future}, will yield
     * the callable's result as its result and provide for
     * cancellation of the underlying task
     * @since 1.6
     */
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
    }

    /**
     * Executes the given task sometime in the future.  The task
     * may execute in a new thread or in an existing pooled thread.
     *
     * If the task cannot be submitted for execution, either because this
     * executor has been shutdown or because its capacity has been reached,
     * the task is handled by the current {@code RejectedExecutionHandler}.
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *         {@code RejectedExecutionHandler}, if the task
     *         cannot be accepted for execution
     * @throws NullPointerException if {@code command} is null
     */
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }    

FutureTask run方法

    
	public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);  // 異常被賦值到成員變量, 通過(guò)get方法獲取結(jié)果或者異常
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }



    /**
     * Causes this future to report an {@link ExecutionException}
     * with the given throwable as its cause, unless this future has
     * already been set or has been cancelled.
     *
     * <p>This method is invoked internally by the {@link #run} method
     * upon failure of the computation.
     *
     * @param t the cause of failure
     */
    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • java8使用filter()取出自己所需數(shù)據(jù)

    java8使用filter()取出自己所需數(shù)據(jù)

    這篇文章主要介紹了java8使用filter()取出自己所需數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • Java中如何讀取和寫(xiě)入zip文件問(wèn)題

    Java中如何讀取和寫(xiě)入zip文件問(wèn)題

    這篇文章主要介紹了Java中如何讀取和寫(xiě)入zip文件問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • SpringBoot中使用Guava實(shí)現(xiàn)單機(jī)令牌桶限流的示例

    SpringBoot中使用Guava實(shí)現(xiàn)單機(jī)令牌桶限流的示例

    本文主要介紹了SpringBoot中使用Guava實(shí)現(xiàn)單機(jī)令牌桶限流的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • php 頁(yè)面之間傳值的三種方法實(shí)例代碼

    php 頁(yè)面之間傳值的三種方法實(shí)例代碼

    網(wǎng)站開(kāi)發(fā)過(guò)程中,我們經(jīng)常需要在不同頁(yè)面之間進(jìn)行值的傳遞。本文章向大家講解PHP頁(yè)面之間傳值的三種方法。需要的碼農(nóng)可以參考一下
    2016-10-10
  • java實(shí)現(xiàn)統(tǒng)計(jì)字符串中字符及子字符串個(gè)數(shù)的方法示例

    java實(shí)現(xiàn)統(tǒng)計(jì)字符串中字符及子字符串個(gè)數(shù)的方法示例

    這篇文章主要介紹了java實(shí)現(xiàn)統(tǒng)計(jì)字符串中字符及子字符串個(gè)數(shù)的方法,涉及java針對(duì)字符串的遍歷、判斷及運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下
    2017-01-01
  • MyBatis-Plus 中 的動(dòng)態(tài)SQL 片段(sqlSegment)詳解

    MyBatis-Plus 中 的動(dòng)態(tài)SQL 片段(sqlSegment)詳解

    MyBatis-Plus的sqlSegment通過(guò)Wrapper動(dòng)態(tài)生成SQL片段,支持XML中${ew.customSqlSegment}引用,結(jié)合Lambda表達(dá)式避免硬編碼,適用于動(dòng)態(tài)查詢(xún)、邏輯刪除等場(chǎng)景,提升代碼可維護(hù)性與靈活性,本文給大家介紹MyBatis-Plus中的動(dòng)態(tài)SQL片段(sqlSegment)講解,感興趣的朋友一起看看吧
    2025-06-06
  • java實(shí)現(xiàn)簡(jiǎn)單的學(xué)生管理系統(tǒng)

    java實(shí)現(xiàn)簡(jiǎn)單的學(xué)生管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)單的學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • 一文帶你搞懂Maven的繼承與聚合

    一文帶你搞懂Maven的繼承與聚合

    這篇文章主要為大家詳細(xì)介紹了Maven的繼承和聚合以及二者的區(qū)別,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2022-07-07
  • SpringBoot Cache緩存概念講解

    SpringBoot Cache緩存概念講解

    這篇文章主要介紹了Springboot cache緩存,使用緩存最關(guān)鍵的一點(diǎn)就是保證緩存與數(shù)據(jù)庫(kù)的數(shù)據(jù)一致性,本文給大家介紹最常用的緩存操作模式,對(duì)Springboot cache緩存操作流程感興趣的朋友一起看看吧
    2022-12-12
  • Java如何接收前端easyui?datagrid傳遞的數(shù)組參數(shù)

    Java如何接收前端easyui?datagrid傳遞的數(shù)組參數(shù)

    這篇文章分享一下怎么在easyui的datagrid刷新表格時(shí),在后端java代碼中接收datagrid傳遞的數(shù)組參數(shù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2023-11-11

最新評(píng)論

阳新县| 罗城| 沾益县| 南通市| 交口县| 磴口县| 溧水县| 嘉荫县| 南江县| 汕头市| 新安县| 正阳县| 霸州市| 开远市| 沙坪坝区| 渝中区| 乐亭县| 武山县| 会宁县| 政和县| 西和县| 成安县| 盘山县| 江门市| 民勤县| 崇礼县| 双流县| 彰化市| 霞浦县| 资阳市| 祥云县| 海口市| 攀枝花市| 华安县| 绥芬河市| 抚松县| 临江市| 大安市| 南京市| 威信县| 寿光市|