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

import java.util.List;

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

	public AcquirableChain(final List<? extends Acquirable<? extends E>> list) {
		this.list = list;
	}

	public boolean acquire() throws E {
		final int length = list.size();
		int i = 0;
		try {
			while (i < length) {
				if (!list.get(i).acquire()) {
					break;
				}
				i++;
			}
		} finally {
			if (i < length) {
				release(i - 1);
			}
		}
		return i >= length;
	}

	private void release(final int length) {
		for (int i = length; i >= 0; i--) {
			list.get(i).release();
		}
	}

	public void release() {
		release(list.size() - 1);
	}

	public List<? extends Acquirable<? extends E>> getList() {
		return list;
	}
	public void setList(final List<? extends Acquirable<? extends E>> list) {
		this.list = list;
	}
}
