Java tutorial
// Copyright (C) 2015 chief8192@gmail.com // // 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 org.chiefly.nautilus.concurrent; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; /** * {@link Callable} which wraps another {@link Callable} and a * {@link CountDownLatch}. */ public class LatchedCallable<V> extends AbstractCallableWrapper<V> { private final CountDownLatch latch; /** * @param callable The {@link Callable} to wrap. * @param latch The {@link CountDownLatch} to use. */ public LatchedCallable(final Callable<V> callable, final CountDownLatch latch) { super(callable); this.latch = Preconditions.checkNotNull(latch); } /** * @param callables The {@link Callable}s to wrap. * @return A {@link Set} of {@link Callable}s wrapped by * {@link LatchedCallable}s. */ public static <V> Set<Callable<V>> wrapAll(final Set<Callable<V>> callables) { /* Create a latch */ final CountDownLatch latch = new CountDownLatch(callables.size()); /* Do the wrapping */ final Set<Callable<V>> wrapped = Sets.newHashSet(); for (final Callable<V> callable : callables) { wrapped.add(new LatchedCallable<V>(callable, latch)); } return wrapped; } /** @see org.chiefly.nautilus.concurrent.AbstractCallableWrapper#onCatch(java.lang.Exception) */ @Override protected V onCatch(final Exception e) throws Exception { throw e; } /** @see org.chiefly.nautilus.concurrent.AbstractCallableWrapper#onFinally() */ @Override protected void onFinally() { this.latch.countDown(); } /** @see org.chiefly.nautilus.concurrent.AbstractCallableWrapper#onReturn(java.lang.Object) */ @Override protected V onReturn(final V result) { return result; } }