0

In BalusC answer of this question he said that

you should not be declaring the Connection, Statement and ResultSet as instance variables at all (major threadsafety problem!)

I suppose he is referring to the situation when you create an instance and then use it in two different threads, but if you don't do so and every method/thread you run creates their own instance, I cannot see the problem... but BalusC seems so categorical about it.

I normally create a class DBaccess with an instance variable conn, that I initialise in the constructor of the class (for example), and then reuse during all the database calls made by this DBaccess instance. I cannot see the threadsafety problem there since the conn variable is not static, but created in each instance of DBaccess. I have been always reluctant to creating the conn variable per each database query because this will request a connection from the pool each time, whereas I always thought it is more efficient to get the connection and do the 2 or 3 database queries I do in a row, without having to get 2 or 3 different connections.

Can someone explain if my understanding of BalusC warning is correct and if using his advise will not create more overload because of the request of connections per single database access?

user1156544
  • 1,725
  • 2
  • 25
  • 51

1 Answers1

0

In BalusC answer, he is talking about a situation where a singleton class is responsible for db access. All threads will make use of this class and the instance variables has to be made thread safe. You are talking about a case where you would instantiate a DBAccess class for each db access. The instance variables are thread safe in this case. But this may not be an efficient solution. In most cases it is optimal to have a singleton serve for the db requests, thats why he has mentioned it that way.

In many of the matured solutions, applications wont deal with connections directly and would delegate it to a framework which internally acquires and closes connections from the underlying connection pool.

L.H
  • 81
  • 6
  • Can you please point out where in his code he is using the singleton pattern? – user1156544 Nov 03 '17 at 15:55
  • I suggested that it might be using singleton pattern. And if they are in fact using singleton pattern, it will be enforced either in the framework or where the object is initialized, and certainly not visible in the piece of code in that answer. – L.H Nov 06 '17 at 03:34
  • I don't think he was using a singleton pattern. – user1156544 Nov 27 '17 at 12:27