为什么 SpringApplicationBuilder.run 是线程安全的?

问题描述 投票:0回答:1

以下代码来自Spring Boot SpringApplictionBuidler。我知道它使用双重检查来实现线程安全。问题是,有必要让run方法线程安全吗?即使其他方法也不是线程安全的。

public ConfigurableApplicationContext run(String... args) {
    if (this.running.get()) {
        // If already created we just return the existing context
        return this.context;
    }
    configureAsChildIfNecessary(args);
    if (this.running.compareAndSet(false, true)) {
        synchronized (this.running) {
            // If not already running copy the sources over and then run.
            this.context = build().run(args);
        }
    }
    return this.context;
}

我在网上搜索过。我想知道的是代码的动机。

java spring-boot concurrency thread-safety
1个回答
0
投票

您确定查看当前来源吗?

3.2 分支的源代码不再包含此内容:

    public ConfigurableApplicationContext run(String... args) {
        if (this.running.get()) {
            // If already created we just return the existing context
            return this.context;
        }
        configureAsChildIfNecessary(args);
        if (this.running.compareAndSet(false, true)) {
            // If not already running copy the sources over and then run.
            this.context = build().run(args);
        }
        return this.context;
    }

大约 8 个月前有一个提交删除了这个:

删除不必要的同步

  • 关于 SpringApplicationBuilder 中的 AtomicBoolean
  • 在 SimpleFormatter 上
  • 在 FileSystemWatcher 中的私有方法中,该方法始终在 同步块
  • 用 ConcurrentHashMap 替换同步保护 HashMap
© www.soinside.com 2019 - 2024. All rights reserved.