How does Spring bean Handle concurrency

前端 未结 4 1687
栀梦
栀梦 2020-12-13 03:16

My web application uses Spring IOC. So all my spring beans will be singletons by default. In case if two requests try to access two different methods of a single class (for

相关标签:
4条回答
  • 2020-12-13 03:27

    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.

    0 讨论(0)
  • 2020-12-13 03:33

    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:

    • thread safe, stateless design using Spring
    • spring mvc declaring all beans singleton
    0 讨论(0)
  • 2020-12-13 03:36

    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

    0 讨论(0)
  • 2020-12-13 03:46

    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".

    0 讨论(0)
提交回复
热议问题