interface ManagedSync
{
	Object acquire() throws InterruptedException;
	void release(Object o);
	Object attempt(long msec) throws InterruptedException;
}

class Pool implements ManagedSync
{
	protected long permits; // current number of permits available
	protected Queue resources;
	
	public Pool()
	{
		permits = 0;
		resources = new Queue();
	}
	
	public synchronized long permits()
	{
		return permits;
	}
	
	public synchronized void release(Object o)
	{
		++permits;
		resources.enqueue(o);
		notify();
	}
	
	public Object acquire() throws InterruptedException
	{
		if (Thread.interrupted()) throw new InterruptedException();
		synchronized(this)
		{
			try
			{
				while (permits <= 0)
					wait();
				--permits;
				return resources.dequeue();
			}
			catch (InterruptedException ie)
			{
				notify();
				throw ie;
			}
		}
	}
	
	public Object acquire(Object o) throws InterruptedException
	{
		if (Thread.interrupted()) throw new InterruptedException();
		synchronized(this)
		{
			try
			{
				while (permits <= 0)
					wait();
				Object obj = resources.extract(o);
				if (obj != null)
				{
					--permits;
					return obj;
				}
				else
					return null;
			}
			catch (InterruptedException ie)
			{
				notify();
				throw ie;
			}
		}
	}
	
	public Object attempt(long msecs) throws InterruptedException
	{
		if (Thread.interrupted()) throw new InterruptedException();
		synchronized(this)
		{
			if (permits > 0)
			{
				--permits;
				return resources.dequeue();
			}
			else if (msecs <= 0)
				return null;
			else
			{
				try
				{
					long startTime = System.currentTimeMillis();
					long waitTime = msecs;
					
					while (true)
					{
						wait(waitTime);
						if (permits > 0)
						{
							--permits;
							return resources.dequeue();
						}
						else
						{
							long now = System.currentTimeMillis();
							waitTime = msecs - (now - startTime);
							if (waitTime <= 0)
								return null;
						}
					}
				}
				catch (InterruptedException ie)
				{
					notify();
					throw ie;
				}
			}
		}
	}
}