[concurrency-interest] Concurrency Architecture

Brian S O'Neill bronee at gmail.com
Sun Jun 14 13:10:05 EDT 2009


There's many ways to do this, but a simple solution that works with your 
current design is to include an atomic "generation" counter. The first 
thing getConnection does is copy the counter value, from a shared 
AtomicInteger, to a local variable. When you synchronize on 
this.generator, check the counter value again. If it is the same, then 
the current thread is the "leader" and is responsible for selecting a 
new server. It increments the AtomicInteger when it is done. Other 
threads will see that the value has changed, and they just use the new 
server instead of selecting one.

Norman Elton wrote:
> 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?
>
> Thanks!
>
> Norman
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>   


More information about the Concurrency-interest mailing list