Let us say we have a class:
@RequestScoped
public class FooService {
private NonThreadSafeGenerator generator = new NonThreadSafeGenerator();
public String generateId() {
return this.generator.generateId();
}
}
And we run our application under some servlet-container. Will it be thread-safe? In other words, is it guaranteed that RequestScoped's bean is always visible only within single thread?
Yes, it is guaranteed. Firstly you can take a look at CDI specification, at 6.3 Normal scopes. Take your time reading it, it takes a bit of time but the conclusion is that normal scoped are basically thread-bound.
Then, to really convince you, let's take a look directly to Weld codebase. All implementations of normal scoped context are based on several abstract predecessor classes. If you do a bit of digging, you can come up with two of them - AbstractBoundContext
and AbstractUnboundContext
. Both use ThreadLocal
to implement an underlying bean store - this is what will guarantee you the thread-based behaviour.