JEE6 @ApplicationScoped bean and concurrency

前端 未结 1 486
借酒劲吻你
借酒劲吻你 2020-12-08 20:57

I need to write a bean that would act as a counter of how many times it was accessed.

I\'m thinking of using @ApplicationScoped bean with AtomicIn

相关标签:
1条回答
  • 2020-12-08 21:37

    In CDI you don't have concurrency management, so @ApplicationScoped simply states the cardinality of the injected object (i.e. instructs the injection engine to create only one instance of your bean and use it across all the application). It does not transform your bean in an EJB, and does not enforce any concurrency constraint.

    So, while the operations in the examples are inherently thread safe, thanks to the AtomicInteger and the synchronized list, the same is not true in general.

    In the general you can:

    • manually synchronize the list accesses through the standard concurrency primitives (as you have done)

    • or use the javax.ejb.Singleton annotation, which instructs the application server to manage concurrency. This transforms your bean in an EJB and by default enforces @ConcurrencyManagement(ConcurrencyManagementType.CONTAINER) and @Lock(LockType.WRITE).

    By the way, @ConcurrencyManagement and @Lock are only available on singleton session beans.

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