001    /*
002     * Copyright (c) 2007-2015 Concurrent, 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    
021    package cascading.management;
022    
023    import java.util.ArrayList;
024    import java.util.Collection;
025    import java.util.List;
026    import java.util.concurrent.Callable;
027    import java.util.concurrent.ExecutorService;
028    import java.util.concurrent.Executors;
029    import java.util.concurrent.Future;
030    import 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     */
038    public 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<Future<Throwable>>();
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      }