package jdf;

import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * Copyright 2010 Jonathan Feinberg
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

 */
/**
 * Synchronize "on an equivalence class"; i.e., if you wish to lock not a
 * specific string, but anything that equals that string, you may
 * 
 * <pre>equivalenceLock.lock("frank"); 
try {
    // whatever 
} finally {
    equivalenceLock.release("frank"); 
}</pre>
 
 * @author Jonathan Feinberg &lt;jdf@pobox.com&gt;
*/
public class EquivalenceLock<T>
{
	private static final Logger LOG = Logger.getLogger(EquivalenceLock.class.getName());
	private static final boolean DEBUG = LOG.isLoggable(Level.FINEST);

	private final Set<T> slots = new HashSet<T>();

	public void lock(final T ticket) throws InterruptedException
	{
		if (DEBUG)
			LOG.finest(Thread.currentThread().getName() + " acquiring lock on tickets");

		synchronized (slots)
		{
			if (DEBUG)
				LOG
						.finest(Thread.currentThread().getName()
								+ " acquired lock on tickets");

			while (slots.contains(ticket))
			{
				if (DEBUG)
					LOG.finest(Thread.currentThread().getName() + " waiting to toss "
							+ ticket);
				slots.wait();
			}

			if (DEBUG)
				LOG.finest(Thread.currentThread().getName() + " accepting " + ticket);
			slots.add(ticket);
		}
	}

	public void release(final T ticket)
	{
		synchronized (slots)
		{
			if (DEBUG)
				LOG.finest(Thread.currentThread().getName() + " tossing " + ticket);
			slots.remove(ticket);
			slots.notifyAll();
		}
	}
}

@@ -872,16 +872,89 @@
  * %3Cpre%3E
+EquivalenceLock%3CString%3E equivalenceLock = new EquivalenceLock%3CString%3E();%0A
 equivale
@@ -1424,65 +1424,120 @@
 %7B%0A%09%09
-if (DEBUG)%0A%09%09%09LOG.finest(Thread.currentThread().getName()
+final String threadName = DEBUG ? Thread.currentThread().getName() : null;%0A%09%09if (DEBUG)%0A%09%09%09LOG.finest(threadName
  + %22
@@ -1619,23 +1619,16 @@
 %09LOG
-%0A%09%09%09%09%09%09
 .finest(
 Thre
@@ -1627,49 +1627,19 @@
 est(
-Thread.currentThread().getName()%0A%09%09%09%09%09%09%09%09
+threadName 
 + %22 
@@ -1741,40 +1741,18 @@
 est(
-Thread.currentThread().get
+thread
 Name
-()
  + %22
@@ -1773,16 +1773,9 @@
 ss %22
-%0A%09%09%09%09%09%09%09
+ 
 + ti
@@ -1838,40 +1838,18 @@
 est(
-Thread.currentThread().get
+thread
 Name
-()
  + %22

clean up formatting