Re: Java DAO pattern: singleton and threadsafe?
koenxjans@gmail.com wrote:
Hello all,
Here's my problem:
I'm working on a legacy J2EE application that uses the DAO pattern
and implements all DAO's [sic] as singletons. There's one abstract DAO
superclass.
That the DAOs are singletons and that there is one abstract superclass are
orthogonal.
But this class holds the connection to the database as an instance
variable.
Which, in my opinion, is not thread safe.
It's a lot easier to make an instance variable thread safe than a static
variable. The problem isn't that there's an instance variable, the problem is
that you're using a singleton. Stop using the class as a singleton.
If multiple clients would make a call simultaneously, the very same
connection
would be used for the different calls, resulting in an exception on
the app server.
I think a different connection should be gotten from the datasource
connection
pool on everycall? And that the datasource itself should be an
instance variable.
I suggest that you provide an SSCCE - a simple, self-contained compilable
example that illustrates the points you're making. All this vague hand-waving
doesn't admit of any useful comment. The example should elucidate the
"singleton-ness" of the approach.
--
Lew