1

I have a class in which I once initialize a database Connection private field. This object instantiation is final and will never change with an another connection. (e.x other database, other user, etc).

I want to execute different operations with this Connection object through different method calls. These methods are called through out different threads for better performance.

I think that using a Connection Pool is useless due to the fact that I only use one Connection. (Or, maybe I'm wrong). Should I use synchronization,

synchronized (mConnection) { }

or something else?

I'm sorry for any miss understanding in advance.

g.kanellis
  • 140
  • 2
  • 10
  • 1
    "These methods are called through out different threads for better performance." - you are aware that you can only do one thing at a time in a given connection? Unless the threads are carefully coordinated you risk race conditions. – Thorbjørn Ravn Andersen Sep 20 '16 at 21:44
  • No I was not aware of that. I'm a newbie in Java's SQL part. So I have to initialize a Connection in each thread accordingly? – g.kanellis Sep 20 '16 at 21:45
  • See: [Is java.sql.Connection thread safe?](http://stackoverflow.com/questions/1531073/is-java-sql-connection-thread-safe) – Andreas Sep 20 '16 at 21:48
  • Yeah I ve already saw that. It refers to connection pools – g.kanellis Sep 20 '16 at 21:48
  • A connection a thread sounds like a good idea. Will that work for you? Also be aware that if you have long periods of inactivity you might run into connections going stale which is simpler to handle in a good connection pool. Do not write the connection pool yourself. – Thorbjørn Ravn Andersen Sep 20 '16 at 22:08
  • @ThorbjørnRavnAndersen Can you explain that in a code-like example? Thanks in advance! – g.kanellis Sep 21 '16 at 08:20
  • Just use a good connection pool, and only get/release connections when you actually need them. – Thorbjørn Ravn Andersen Sep 21 '16 at 08:52
  • You may want to just design it as simple as possible, and create a connection when you need it and close it when done. You can then see what the overhead is and if you need the extra complexity from a connection pool. – Thorbjørn Ravn Andersen Sep 21 '16 at 09:43

0 Answers0