/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * 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.
 */
package woolpack.utils;

import java.util.concurrent.Semaphore;

import javax.xml.transform.Result;
import javax.xml.transform.Source;

/**
 * 委譲先から取得した{@link XmlTransformer}を再利用しかつ、
 * 同時に動作する複数のスレッドで使用できるようにラップした
 * {@link XmlTransformerFactory}。
 * 適用しているパターン：Proxy。
 * 
 * @author nakamura
 * 
 */
public class XmlTransformerFactorySemaphoreImpl implements
		XmlTransformerFactory {
	private final Semaphore[] semaphoreArray;

	private final XmlTransformer[] transformerArray;

	// position の原子性を厳密に制御する必要はない。
	private int position;

	/**
	 * コンストラクタ。
	 * 
	 * @param factory
	 *            委譲先。
	 * @param length
	 *            並行実行数。
	 * @throws NullPointerException
	 *             factory が null の場合。
	 * @throws IllegalArgumentException
	 *             toNodeCount がゼロ以下の場合。
	 */
	public XmlTransformerFactorySemaphoreImpl(
			final XmlTransformerFactory factory, final int length) {
		if (length < 1) {
			throw new IllegalArgumentException(
					"length must be equals or more than 1 but " + length);
		}
		CheckUtils.checkNotNull(factory);

		position = 0;
		semaphoreArray = new Semaphore[length];
		transformerArray = new XmlTransformer[length];
		for (int i = 0; i < length; i++) {
			semaphoreArray[i] = new Semaphore(1);
			synchronized (factory) {
				transformerArray[i] = factory.newInstance();
			}
		}
	}

	public XmlTransformer newInstance() {
		return new XmlTransformer() {
			public void transform(final Source xmlSource,
					final Result outputTarget) {
				int i = position;
				while (true) {
					for (; i < transformerArray.length; i++) {
						if (semaphoreArray[i].tryAcquire()) {
							try {
								transformerArray[i].transform(xmlSource,
										outputTarget);
								return;
							} finally {
								semaphoreArray[i].release();
								position = (i + 1) % transformerArray.length;
							}
						}
						Thread.yield();
					}
					i = 0;
				}
			}
		};
	}
}
