How does Spring bean Handle concurrency

可紊 提交于 2019-11-30 00:21:47
Tomasz Nurkiewicz

You must first understand when concurrency can cause problems. If your Spring bean is stateless (it doesn't have any fields, all fields are final or all of them are assigned only once), multiple threads can safely use the same bean, or even the same method.

See also:

If the bean is a singleton, then Spring will give you the same instance in any thread. It's up to you to make that bean thread-safe. Since it's a singleton, you'd be best off making that class stateless.

As others have already suggested, Spring is going to provide the same instance to all the threads in case of "singleton" beans.

What you need to understand is that threads do all the work in a system by executing the code while objects provide state and behavior (code). So it is indeed possible for multiple threads (requests in your case), to be concurrently running same methods in a singleton bean. You can either make such beans stateless as Tomasz suggested or otherwise make them "thread-safe".

Java singleton and spring singleton are different. Spring singleton scope will be available within context.

Java singleton scope will be in JVM class loader. Hence concurrent request possible only through spring contexts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!