Reputation: 1480
I want to save a file-system structure in a Application Scoped Bean, because this is valid for all clients. Each client is allowed to read this bean.
But the data has to be refreshed 4 times a day, because the filesystem may be changed.
Is it possible to use a application scoped bean for this use case or are there problems with thread safety when refreshing the data? What is the alternative way? Singleton?
Upvotes: 2
Views: 1767
Reputation: 740
All that the JSF or CDI scoped annotations will do for you is control the lifecycle of the object. Namely, when it is first referenced, the bean will be instantiated, and execute any injections or postconstruct method. In the case of ApplicationScoped it will also ensure that only one copy of the object will be produced (Unless of course you explicitly create one).
So with that being said, there is nothing different about an instance of your class versus one that is not container-managed as it relates to thread-safety. So if you change the attributes of the object while some other thread is assuming them to be consistent, you will have an issue. IMO it's an issue of synchronized access. Any operations that need to be atomic and have a consistent view of the object should take out some form of exclusive lock.
Some support from the JavaBeans spec -
2.8 Multi-Threading Java Beans should assume that they are running in a multi-threaded environment and that several different threads may be simultaneously delivering events and/or calling methods and/or setting properties. It is the responsibility of each java bean developer to make sure that their bean behaves properly under multi-threaded access. For simple beans this can generally be handled by simply making all the methods “synchronized”
Upvotes: 2