Why is SpringApplicationBuilder.run made as thread-safe?

24 Views Asked by At

The following codes come from Spring Boot SpringApplictionBuidler. I know it uses double-checking to implement thread-safe. The question is that, is it necessary to make the run method thread-safe? Even other methods are not thread safe.

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;
}

I have searched on the internet. What I want to know is the motive of the codes.

1

There are 1 best solutions below

4
Thomas Kläger On

Are you sure that you look at the current sources?

The sources for the 3.2 branch don't contain this anymore:

    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;
    }

And there was a commit about 8 months ago that removed this:

Remove unnecessary synchronization

  • on AtomicBoolean in SpringApplicationBuilder
  • on SimpleFormatter
  • in a private method in FileSystemWatcher which is always called in a synchronized block
  • Replaced synchronized guarded HashMap with ConcurrentHashMap