- If ArrayList and haspMap are not thread safe ,then how come every one using these data structures in every restful service (mirco services) in spring boot?
assuming standard java applications follow thread per request model.
- how these non thread safe data structures behave in reactive programing , don’t we need to worry about threads ?
The non-thread-safe means that when multiple threads write into the same container, it will go wrong, like this:
public void demo1() {
List<String> list = new ArrayList();
ExecutorService executor = Executors.newFixedThreadPool(6);
for (int i = 0; i < 100; i++) {
// just don't do this, it terrible
executor.submit(() -> {
list.add(UUID.randomUUID().toString());
});
}
}
But if a thread writes its own container that is fine. Here is another example.
This is most common situation in real life, each request was an independent thread, so it doesn’t have thead-safe issue.
public void demo2() {
ExecutorService executor = Executors.newFixedThreadPool(6);
for (int i = 0; i < 100; i++) {
executor.submit(() -> {
// this is fine.
List<String> list = new ArrayList();
list.add(UUID.randomUUID().toString());
});
}
}
If you do need to deal with a collection in multiple threads, the JDK provider a set of thread-safe container. For example, you can use Vector
or CopyOnWriteArrayList
to replace ArrayList
, and use ConcurrentHashMap
to HashMap
.
public void demo3() {
// "CopyOnWriteArrayList " is thread-safe
List<String> list = new CopyOnWriteArrayList();
ExecutorService executor = Executors.newFixedThreadPool(6);
for (int i = 0; i < 100; i++) {
// this is also fine
executor.submit(() -> {
list.add(UUID.randomUUID().toString());
});
}
}
what do you mean “everyone”?
That depends on what the code is doing. If the code is only reading the data but does not modify the content there should be no issues.
If you are mutating instances from different threads, you will need to lock. Otherwise you won’t. You need to edit your question to explain exactly what situation you’re asking about.
In most applications that I know requests are independent of each other and most processing in a request is done serially by a single thread (i.e. threads are only use to be able to process multiple requests, each request is handled by a single thread.) Reactive programming is no exception to this rule. Only when you need to process parts of a single request in parallel will you need thread safe data structures for those parts. Java 21 with its virtual threads helps to further engrain this approach.
Be careful with your spelling of important technical terms.