This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt on-line!
See this thread for details.
The moose likes Java in General and the fly likes What's the Solution Here? Connection Pool Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "What Watch "What New topic

What's the Solution Here? Connection Pool Problem

Dan Bizman
Ranch Hand

Joined: Feb 25, 2003
Posts: 387
I've made a connection pool manager, and everything works well except for one method:

I can't make this method synchronized as it is from an interface. I can't figure out how to make this all work. i don't want a huge synchronized block around it because:
1. If it needs to queue, that will hold the block for as long as it needs to wait
2. If I synch on the idleConnections List, then I can't add a new connection to it if I need to (if someone else frees up)
But I need to somehow be able to check if it's empty, if no then pull from it and return, if yes add to the pool, if that throws an exception then queue till we get one, otherwise pull from that pool, add it to active list and return.
Dan Bizman
Ranch Hand

Joined: Feb 25, 2003
Posts: 387
This is the best I could come up with so far:
karl koch
Ranch Hand

Joined: May 25, 2001
Posts: 388
as far as i see, a thread could be interrupted between the check of size and the synchronization.
even if the size is 0 and you add a connection, then some other thread could get this connection you just added.

so you would need to make the whole thing synchronized (check size, then remove connection).
you could use a wait()/notifyAll() to make threads wait if the queue is empty.
Dan Bizman
Ranch Hand

Joined: Feb 25, 2003
Posts: 387
yeah, I have the solution, I believe. I'm changing addConnections so it returns a connection and takes a boolean. If the boolean is true it'll add the new connection straight to activeConnections and return the reference to that connection. If it's not true, it adds it to idleConnections and returns null. If it can't add the connection it throws the exception same as always. This way I am able to do the size check and create all in a synchronized block (I'll do a check to see if it is still of size zero inside the synched block in the addConnections method - if it's not, i.e. someone put a connection back in there, then I'll return that connection)
I agree. Here's the link:
subject: What's the Solution Here? Connection Pool Problem
It's not a secret anymore!