简体   繁体   中英

Threading on JPA Spring boot

Hi I am trying to loop and save the objects to database using JPA repository. I wanted to use thread here,but while threading multiple objects saves at one time on same table wether the primary id which is auto generated will get collide?

As far as I know you don't need to worry about database-level data race since database handles multiple access at the same time, to put it simply you're good to go.

there's another issue makes me worried.还有一个问题让我很担心。 I'm assuming you're developing a web application that runs on a web-server am I right? Since web-server itself creates min 10 threads to receive http requests from the internet, creating extra threads in the code may not be a good idea.

let's say that once you call a method A() it creates extra 1 thread, and imagine there're 3 request was made to the same endpoint so web server assigns each request to a thread and in each thread the method A() is called which in this case you'll have 3 more new threads, in case you have high traffic you may end up with a situation which there're many threads more than your computer handles.

Creating a common thread pool for common use might be an option only if it's application level (declaring static thread pool)
Or
if the Job is not needed to be applied instantly, you can write another batch program with many threads and can use Redis-like message passing application to handle communication. Thus you can remove the barrier sitting in the high-request and scalability.

You do not need to loop in order to save the data. You can save your entities in a collection and call the jpa saveAll() method.

repository.saveAll(Iterable<S> entities)

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