I am developing an application that will run under spring boot context with tomcat. This project connects on startup to Kafka, pulls messages and process them. The tomcat is used for some management APIs.
When Spring is loading, it connects with Kafka by several threads. Each thread is autowired with a spring bean that handles a message. This bean of-course autowired with more beans etc..
Do I need to consider concurrency issues? Synchronize stuff? use concurrent types such as ConcurrentHashMap instead of normal HashMap for example?
In spring, the bean is singleton by default. The methods of bean can be called by several threads in concurrently. In every method, you don't need to care about concurrency. But if you want to save the data in some other places, like bean members of other data object, you should care about the concurrency for those data holder.
In this example:
@Service
public class SomeService {
public Map handle(Map dataHolder) {...}
}
@Service
public class OtherSerice {
@Inject SomeService serv1;
Map theDataNotSafe = new HashMap();
public Map func() {
Map theData = new HashMap();
serv1.handle(theData); // thread safe,
serv1.handle(theDataNotSafe); // not thread safe
}
}
The OtherService.func() function will call SomeService.handle(..)
. Function serv1.handle(theDataNotSafe);
is not thread safe, because there are several threads will call the function with the same HashMap
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With