Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What's the Solution Here? Connection Pool Problem

 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Help!
 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the best I could come up with so far:
 
karl koch
Ranch Hand
Posts: 388
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
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.
k
 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic