    001/*
    002 * Copyright (c) 2007-2017 Xplenty, Inc. All Rights Reserved.
    003 *
    004 * Project and contact information: http://www.cascading.org/
    005 *
    006 * This file is part of the Cascading project.
    007 *
    008 * Licensed under the Apache License, Version 2.0 (the "License");
    009 * you may not use this file except in compliance with the License.
    010 * You may obtain a copy of the License at
    011 *
    012 *     http://www.apache.org/licenses/LICENSE-2.0
    013 *
    014 * Unless required by applicable law or agreed to in writing, software
    015 * distributed under the License is distributed on an "AS IS" BASIS,
    016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    017 * See the License for the specific language governing permissions and
    018 * limitations under the License.
    019 */
    020
    021package cascading.management;
    022
    023import java.util.ArrayList;
    024import java.util.Collection;
    025import java.util.List;
    026import java.util.concurrent.Callable;
    027import java.util.concurrent.ExecutorService;
    028import java.util.concurrent.Executors;
    029import java.util.concurrent.Future;
    030import java.util.concurrent.TimeUnit;
    031
    032/**
    033 * Class UnitOfWorkExecutorStrategy uses a simple {@link Executors#newFixedThreadPool(int)} {@link ExecutorService}
    034 * to spawn threads.
    035 * <p/>
    036 * This is the default spawn strategy.
    037 */
    038public class UnitOfWorkExecutorStrategy implements UnitOfWorkSpawnStrategy
    039  {
    040  private ExecutorService executor;
    041
    042  public List<Future<Throwable>> start( UnitOfWork unitOfWork, int maxConcurrentThreads, Collection<Callable<Throwable>> values ) throws InterruptedException
    043    {
    044    executor = Executors.newFixedThreadPool( maxConcurrentThreads );
    045
    046    List<Future<Throwable>> futures = new ArrayList<>();
    047
    048    for( Callable<Throwable> value : values )
    049      futures.add( executor.submit( value ) );
    050
    051    executor.shutdown(); // don't accept any more work
    052
    053    return futures;
    054    }
    055
    056  @Override
    057  public boolean isCompleted( UnitOfWork unitOfWork )
    058    {
    059    return executor == null || executor.isTerminated();
    060    }
    061
    062  @Override
    063  public void complete( UnitOfWork unitOfWork, int duration, TimeUnit unit ) throws InterruptedException
    064    {
    065    if( executor == null )
    066      return;
    067
    068    executor.awaitTermination( duration, unit );
    069    }
    070  }