/*
 * 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.concurrent;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import woolpack.utils.CheckUtils;

/**
 * コンストラクタ引数で指定された{@link Acquirable}を順に
 * {@link Acquirable#acquire()}する{@link Acquirable}。
 * {@link Acquirable#acquire()}による実行権の取得に失敗した場合、
 * 既に実行権を取得した{@link Acquirable}
 * を逆順に{@link Acquirable#release()}する。
 * 
 * @author nakamura
 * 
 */
public class AcquirableChain implements Acquirable {
	private final Acquirable[] array;

	/**
	 * コンストラクタ。
	 * 
	 * @param acquirables
	 *            {@link Acquirable}の配列。
	 * @throws NullPointerException
	 *             引数が null の場合。
	 */
	public AcquirableChain(final Acquirable... acquirables) {
		CheckUtils.checkNotNull(acquirables);
		this.array = (Acquirable[]) acquirables.clone();
	}

	public boolean acquire() {
		int i = 0;
		try {
			while (i < array.length) {
				if (!array[i].acquire()) {
					break;
				}
				i++;
			}
		} finally {
			if (i < array.length) {
				release(i - 1);
			}
		}
		return i >= array.length;
	}

	private void release(final int length) {
		for (int i = length; i >= 0; i--) {
			array[i].release();
		}
	}

	public void release() {
		release(array.length - 1);
	}

	public List<Acquirable> getArray() {
		return Collections.unmodifiableList(Arrays.asList(array));
	}
}
