I declared a Spring bean that checks my mail server every so and so. If there is mail, it extracts it and tries to extract the attached files into it. These files are then sent to Uploader, which saves them safely. The user uploader is also declared as a Spring bean. The third bean associates the sender of the email with the file name and stores it in the database.
It turned out that when several people tried to send email at the same time, a bunch of messy things happened. Entries in the database received invalid file names. Some have not received file names, etc.
I explained this problem by the fact that beans is bound to singleton by default. This means that a bunch of threads are likely to get confused at the same time with the same instance. The question is how to solve this problem.
If I synchronize all sensitive methods, then all the threads will add up and wait for each other, which is not against the whole idea of โโmultithreading.
On the other hand, viewing the beans request for a "request" will create new instances of each of them, which is also not very good when it comes to memory consumption and thread scheduling.
I'm confused. What should I do?
java spring multithreading
user802232
source share