Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DataSouce in Hashmap. Is it ok?

 
Joseph Hatton
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hashmap map = new Hashmap();
Context ctx = new InitialContext();
DataSource src = (DataSource) ctx.lookup("java:comp/env/jdbc/prod");
map.put("dsName",src);

I noticed in this code that the datasource object was put into a hashmap. To me, it seem little unorthodox because I haven't seen this done before. Is there any danger or ramifications of putting the datasource object in a Hashmap or collection?

Thanks in advance.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35279
384
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joseph,
While most people look up the DataSource multiple times, it is ok to cache a copy. It is common to cache remote interfaces for EJBs and this is the same idea. You just need to beware of not caching Connections.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35279
384
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Joseph",

We're pleased to have you here with us in the JDBC forum, but there are a few rules that need to be followed, and one is that proper names are required. Please take a look at the JavaRanch Naming Policy and adjust your display name to match it.

In particular, your display name must be a first and a last name separated by a space character, and must not be obviously fictitious.

Thanks,
Jeanne
Forum Bartender
 
Tony Yan
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Putting cached DataSource in a collection is a good practice. However, you may want to consider to synchronize the HashMap or use Hashtable instead. In a multi-threaded env., you can get into problems otherwise.
 
Robert Hayes
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This practice is actually coded in the ServiceLocator pattern of the J2EE patterns book ( I think that book is on-line btw).

I tried to do this with some non-JDBC related connections but ran into some "stale" connection problems, so just beware if you start using the technique for other things.

Oh... and if you want to do what Tony is suggesting it can look something like this:


[ December 10, 2004: Message edited by: Robert Hayes ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic