简体   繁体   中英

Tasks submitted to Fixed threadpool ExecutorService are threadsafe?

The tasks submitted uses resource beans from a spring container. Are the methods in the beans thread safe when accessed by concurrent threads of a executor service?

They aren't thread-safe by definition. If your Spring beans are immutable, stateless or properly synchronized (99% of the cases) they are thread safe. Here are few examples of thread-safe Spring beans:

Only final fields:

public class ImmutableService {

    private final Dependency dep;

    @Autowired
    public StatelessService(Dependency dep) {
        this.dep = dep;
    }

    public Foo foo() {
        return dep.foo();
    }

}

Field is modified only during creation, effectively final:

public class EffectivelyImmutableService {

    @Autowired
    private final Dependency dep;

    public Foo foo() {
        return dep.foo();
    }

}

No state, typical utility class:

public class StatelessService {

    public Foo foo() {
        return new Foo();
    }

}

Non-atomic operations are synchronized :

public class SynchronizedService {

    private int counter;

    public synchronized Foo foo() {
        return new Foo(counter++);
    }

}

AtomicInteger to avoid explicit synchronization (field is final , but the object isn't):

public class AtomicService {

    private final AtomicInteger counter = new AtomicInteger();

    public Foo foo() {
        return new Foo(counter.incrementAndGet());
    }

}

Note that this rule applies to all use-cases, not only to tasks using Spring beans in thread pool. For instance if your servlets/controllers use Spring beans, they have to be thread safe as well.

If you were to manually start two threads accessing these beans, would the access be threadsafe then? An executor service does no magic and does not change anything about the code running in its threads. If accessing the beans is not threadsafe from two manually started threads, it's not threadsafe when the code is executed by threads managed by an Executor either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM