[concurrency-interest] Concurrency Architecture

Norman Elton normelton at gmail.com
Sun Jun 14 12:37:13 EDT 2009

I've been using the java.util.concurrent classes over the past few
years, they've worked well for every circumstance I could throw at
them. Today, I've stumbled upon a case that I just can't figure out
how best to tackle.

I've got a connection generator which builds and returns connections
to a server. In case of failover, I'm maintaining a list of possible
servers to which it can generate connections. My wrapper
getConnection() method takes this into account by first attempting a
connection to the "current" server. If that times out, it scans the
list for a new "current" server.

Here's some pseudocode:

public Connection getConnection() {
	try {
		return this.generator.getConnection();
	} catch (TimeoutException e) {
	synchronized(this.generator) {
		foreach (this.servers as curr_server) {
			try {
				this.generator.server = curr_server;
				return this.generator.getConnection();
			} catch (TimeoutException e) {
	throw new Exception("Sorry, couldn't find a server");

In this case, if three threads simultaneously call getConnection(),
they will all timeout and hit the synchronized block together. The
first one will identify a new server, but the other two have no way to
know that a new server has been identified. They each will loop
through the possible servers.

I'm looking for some way for all threads to be able to call the first
part of the procedure (attempt a connection to the current server). If
that fails, then the first thread will attempt to find a new server,
while others wait for the result.

I've dug through all the possible types of locks, nothing quite meets
the need. Of course, I could be wrong! Can anyone think of a good way
to tackle these requirements?



More information about the Concurrency-interest mailing list