首页 > 解决方案 > 为什么tomcat最新代码在main方法中使用同步

问题描述

查看Tomcat的最新代码,在main方法中找到,它在初始化引导实例时使用了同步。

synchronized (daemonLock) {
        if (daemon == null) {
            // Don't set daemon until init() has completed
            Bootstrap bootstrap = new Bootstrap();
            try {
                bootstrap.init();
            } catch (Throwable t) {
                handleThrowable(t);
                t.printStackTrace();
                return;
            }
            daemon = bootstrap;
        } else {
            // When running as a service the call to stop will be on a new
            // thread so make sure the correct class loader is used to
            // prevent a range of class not found exceptions.
            Thread.currentThread().setContextClassLoader(daemon.catalinaLoader);
        }
    } 

标签: javatomcatsource-code-protection

解决方案


TL;DR:Mark Thomas 减少了来自静态代码分析工具 SpotBugs 的警告消息。

正如您在 Tomcat SVN 日志中看到的那样,同步是在修订版 1826336 中引入的:https ://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/startup/Bootstrap.java?r1=1826335&r2 =1826336&

用 评论Fix some more SpotBugs warnings

当在 Bootstrap.java 的修订版 1826335 上运行 SpotBugs 并激活所有模块和最大灵敏度/详细度时,我可能已经复制了他已修复的警告:

Bug: Incorrect lazy initialization of static field Bootstrap.daemon in Bootstrap.main(String[])

This method contains an unsynchronized lazy initialization of a non-volatile static field. Because the compiler or processor may reorder instructions, threads are not guaranteed to see a completely initialized object, if the method can be called by multiple threads. You can make the field volatile to correct the problem. For more information, see the Java Memory Model web site. 

Rank: Of Concern (17), confidence: Low
Pattern: LI_LAZY_INIT_STATIC 
Type: LI, Category: MT_CORRECTNESS (Multithreaded correctness)

推荐阅读