Created
April 12, 2016 13:04
-
-
Save miere/cdd07e72ebcd02286e28bd297b05475c to your computer and use it in GitHub Desktop.
Convenient abstraction to deal with Threads and ExecutorServices.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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