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.CountDownLatch; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; /** * {@link Runnable} which wraps another {@link Runnable} and a * {@link CountDownLatch}. */ public class LatchedRunnable extends AbstractRunnableWrapper { private final CountDownLatch latch; /** * @param runnable The {@link Runnable} to wrap. * @param latch The {@link CountDownLatch} to use. */ public LatchedRunnable(final Runnable runnable, final CountDownLatch latch) { super(runnable); this.latch = Preconditions.checkNotNull(latch); } /** * @param runnables The {@link Runnable}s to wrap. * @return A {@link Set} of {@link Runnable}s wrapped by * {@link LatchedRunnable}s. */ public static <V> Set<Runnable> wrapAll(final Set<Runnable> runnables) { /* Create a latch */ final CountDownLatch latch = new CountDownLatch(runnables.size()); /* Do the wrapping */ final Set<Runnable> wrapped = Sets.newHashSet(); for (final Runnable runnable : runnables) { wrapped.add(new LatchedRunnable(runnable, latch)); } return wrapped; } /** @see org.chiefly.nautilus.concurrent.AbstractRunnableWrapper#onFinally() */ @Override protected void onFinally() { this.latch.countDown(); } /** @see org.chiefly.nautilus.concurrent.AbstractRunnableWrapper#onReturn() */ @Override protected void onReturn() { /* does nothing */ } }