File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes How to properly declare a DataSource object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "How to properly declare a DataSource object" Watch "How to properly declare a DataSource object" New topic

How to properly declare a DataSource object

James Davison

Joined: Mar 28, 2004
Posts: 27
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?
Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
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.

Consultant, Sima Solutions
I agree. Here's the link:
subject: How to properly declare a DataSource object
It's not a secret anymore!