I need to create several data access objects. Is it okay to retrieve and maintain a DataSource object in the superclass as a static variable and have all subclasses access that DataSource object? Any threading issues I should be concerned about?
Joined: Feb 15, 2005
I've done this a lot in my applications, but after reading this article:
I don't think I will any more. Below is a quote from the article:
When the Service Locator pattern was first developed for J2EE 1.2, caching references was a good idea, or at least it didn't hurt anything. But starting in J2EE 1.3, application resource names are component-scoped, not global. Because each component is mapped separately, two components which happen to use the same resource name may not necessarily be bound to the same container resource. It may be overloaded such that components which use the same name map to different resources.
A service locator that caches references will cause a J2EE 1.3 (and later) application with an overloaded resource name to work incorrectly. It will deploy successfully and seem to run correctly, but will run into subtle and difficult-to-diagnose problems when a component uses the wrong resource. This is because the service locator will cache the resource for whichever component uses the overloaded name first. When a differently bound component uses the same resource name, it will not receive the resource it is bound to; it will receive the resource in the cache, which is the first component's resource.