|
| 1 | +/* |
| 2 | + * #%L |
| 3 | + * ImgLib2: a general-purpose, multidimensional image processing library. |
| 4 | + * %% |
| 5 | + * Copyright (C) 2009 - 2021 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld, |
| 6 | + * John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke, |
| 7 | + * Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner, |
| 8 | + * Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert, |
| 9 | + * Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin, |
| 10 | + * Jean-Yves Tinevez and Michael Zinsmaier. |
| 11 | + * %% |
| 12 | + * Redistribution and use in source and binary forms, with or without |
| 13 | + * modification, are permitted provided that the following conditions are met: |
| 14 | + * |
| 15 | + * 1. Redistributions of source code must retain the above copyright notice, |
| 16 | + * this list of conditions and the following disclaimer. |
| 17 | + * 2. Redistributions in binary form must reproduce the above copyright notice, |
| 18 | + * this list of conditions and the following disclaimer in the documentation |
| 19 | + * and/or other materials provided with the distribution. |
| 20 | + * |
| 21 | + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 22 | + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 23 | + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 24 | + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE |
| 25 | + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 26 | + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 27 | + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 28 | + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 29 | + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 30 | + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 31 | + * POSSIBILITY OF SUCH DAMAGE. |
| 32 | + * #L% |
| 33 | + */ |
| 34 | +package org.scijava.concurrent; |
| 35 | + |
| 36 | +import java.lang.reflect.Array; |
| 37 | +import java.util.ArrayList; |
| 38 | +import java.util.List; |
| 39 | +import java.util.concurrent.Callable; |
| 40 | +import java.util.concurrent.ExecutionException; |
| 41 | +import java.util.concurrent.ExecutorService; |
| 42 | +import java.util.concurrent.Executors; |
| 43 | +import java.util.concurrent.ForkJoinPool; |
| 44 | +import java.util.concurrent.Future; |
| 45 | +import java.util.concurrent.ThreadPoolExecutor; |
| 46 | +import java.util.function.Consumer; |
| 47 | +import java.util.function.Function; |
| 48 | + |
| 49 | +/** |
| 50 | + * A {@link TaskExecutor} that wraps around a given {@link ExecutorService}. |
| 51 | + */ |
| 52 | +public class DefaultTaskExecutor implements TaskExecutor |
| 53 | +{ |
| 54 | + |
| 55 | + private final ExecutorService executorService; |
| 56 | + |
| 57 | + public DefaultTaskExecutor( final ExecutorService executorService ) |
| 58 | + { |
| 59 | + this.executorService = executorService; |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + public ExecutorService getExecutorService() |
| 64 | + { |
| 65 | + return executorService; |
| 66 | + } |
| 67 | + |
| 68 | + @Override |
| 69 | + public int getParallelism() |
| 70 | + { |
| 71 | + if ( executorService instanceof ForkJoinPool ) |
| 72 | + return ( ( ForkJoinPool ) executorService ).getParallelism(); |
| 73 | + else if ( executorService instanceof ThreadPoolExecutor ) |
| 74 | + return Math.max( 1, ( ( ThreadPoolExecutor ) executorService ).getCorePoolSize() ); |
| 75 | + else if ( executorService instanceof ForkJoinExecutorService ) |
| 76 | + return ( ( ForkJoinExecutorService ) executorService ).getParallelism(); |
| 77 | + else if ( executorService instanceof SequentialExecutorService ) |
| 78 | + return ( ( SequentialExecutorService ) executorService ).getParallelism(); |
| 79 | + return Runtime.getRuntime().availableProcessors(); |
| 80 | + } |
| 81 | + |
| 82 | + @Override |
| 83 | + public void runAll( final List< Runnable > tasks ) |
| 84 | + { |
| 85 | + final List< Callable< Object > > callables = new ArrayList<>( tasks.size() ); |
| 86 | + // use for-loop because stream with collect(Collectors.toList) is slow. |
| 87 | + for ( Runnable task : tasks ) |
| 88 | + callables.add( Executors.callable( task ) ); |
| 89 | + invokeAllIgnoreResults( callables ); |
| 90 | + } |
| 91 | + |
| 92 | + @Override |
| 93 | + public int suggestNumberOfTasks() |
| 94 | + { |
| 95 | + int parallelism = getParallelism(); |
| 96 | + return ( parallelism == 1 ) ? 1 : ( int ) Math.min( ( long ) parallelism * 4L, ( long ) Integer.MAX_VALUE ); |
| 97 | + } |
| 98 | + |
| 99 | + @Override |
| 100 | + public < T > void forEach( final List< ? extends T > parameters, final Consumer< ? super T > task ) |
| 101 | + { |
| 102 | + final List< Callable< Object > > callables = new ArrayList<>( parameters.size() ); |
| 103 | + // use for-loop because stream with collect(Collectors.toList) is slow. |
| 104 | + for ( T parameter : parameters ) |
| 105 | + callables.add( () -> { |
| 106 | + task.accept( parameter ); |
| 107 | + return null; |
| 108 | + } ); |
| 109 | + invokeAllIgnoreResults( callables ); |
| 110 | + } |
| 111 | + |
| 112 | + @Override |
| 113 | + public < T, R > List< R > forEachApply( List< ? extends T > parameters, Function< ? super T, ? extends R > task ) |
| 114 | + { |
| 115 | + final List< Callable< R > > callables = new ArrayList<>( parameters.size() ); |
| 116 | + // use for-loop because stream with collect(Collectors.toList) is slow. |
| 117 | + for ( T parameter : parameters ) |
| 118 | + callables.add( () -> task.apply( parameter ) ); |
| 119 | + try |
| 120 | + { |
| 121 | + final List< Future< R > > futures = executorService.invokeAll( callables ); |
| 122 | + final List< R > results = new ArrayList<>( futures.size() ); |
| 123 | + for ( Future< R > future : futures ) |
| 124 | + results.add( future.get() ); |
| 125 | + return results; |
| 126 | + } |
| 127 | + catch ( InterruptedException | ExecutionException e ) |
| 128 | + { |
| 129 | + throw unwrapExecutionException( e ); |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + private void invokeAllIgnoreResults( final List< Callable< Object > > callables ) |
| 134 | + { |
| 135 | + try |
| 136 | + { |
| 137 | + final List< Future< Object > > futures = executorService.invokeAll( callables ); |
| 138 | + for ( Future< Object > future : futures ) |
| 139 | + future.get(); |
| 140 | + } |
| 141 | + catch ( InterruptedException | ExecutionException e ) |
| 142 | + { |
| 143 | + throw unwrapExecutionException( e ); |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + /** |
| 148 | + * {@link ExecutorService} wrap all exceptions thrown by any task into a |
| 149 | + * {@link ExecutionException}, this makes the stack traces rather hard to |
| 150 | + * read. This method unwraps the {@link ExecutionException} and thereby |
| 151 | + * reveals the original exception, and ensures it's complete stack trace. |
| 152 | + */ |
| 153 | + private RuntimeException unwrapExecutionException( Throwable e ) |
| 154 | + { |
| 155 | + if ( e instanceof ExecutionException ) |
| 156 | + { |
| 157 | + final Throwable cause = e.getCause(); |
| 158 | + cause.setStackTrace( concatenate( cause.getStackTrace(), e.getStackTrace() ) ); |
| 159 | + e = cause; |
| 160 | + } |
| 161 | + if ( e instanceof RuntimeException ) |
| 162 | + throw ( RuntimeException ) e; |
| 163 | + else |
| 164 | + return new RuntimeException( e ); |
| 165 | + } |
| 166 | + |
| 167 | + private < T > T[] concatenate( final T[] a, final T[] b ) |
| 168 | + { |
| 169 | + int aLen = a.length; |
| 170 | + int bLen = b.length; |
| 171 | + @SuppressWarnings( "unchecked" ) |
| 172 | + T[] c = ( T[] ) Array.newInstance( a.getClass().getComponentType(), aLen + bLen ); |
| 173 | + System.arraycopy( a, 0, c, 0, aLen ); |
| 174 | + System.arraycopy( b, 0, c, aLen, bLen ); |
| 175 | + return c; |
| 176 | + } |
| 177 | + |
| 178 | + @Override |
| 179 | + public void close() |
| 180 | + { |
| 181 | + executorService.shutdown(); |
| 182 | + } |
| 183 | +} |
0 commit comments