Skip to content

Instantly share code, notes, and snippets.

@miere
Created April 12, 2016 13:04
Show Gist options
  • Select an option

  • Save miere/cdd07e72ebcd02286e28bd297b05475c to your computer and use it in GitHub Desktop.

Select an option

Save miere/cdd07e72ebcd02286e28bd297b05475c to your computer and use it in GitHub Desktop.
Convenient abstraction to deal with Threads and ExecutorServices.
package sizebay.publictools;
import lombok.RequiredArgsConstructor;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
*
*/
@RequiredArgsConstructor
public class Threads {
final Queue<Future<?>> asyncJobs = new ArrayDeque<>();
final ExecutorService executorService;
public static Threads elasticPool() {
return new Threads( Executors.newCachedThreadPool() );
}
public static Threads fixedPool( int numberOfThreads ) {
return new Threads( Executors.newFixedThreadPool( numberOfThreads ) );
}
public void submit( Runnable runnable ) {
final Future<?> future = executorService.submit(runnable);
asyncJobs.add( future );
}
public void shutdown(){
try {
Future<?> future = null;
while ((future = asyncJobs.poll()) != null)
future.get();
executorService.shutdownNow();
} catch ( final Exception cause ) {
throw new RuntimeException(cause);
}
}
}
public class ThreadsSample {
public static void main( String[] args ) {
Threads threads = Threads.elastic();
threads.submit( () -> {
for ( long i=0; i<100000000000; i++)
LockSupport.parkNanos( 2l );
})
threads.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment