Want ThreadPoolExecutor to execute tasks instantly

threadpoolexecutor python
threadpoolexecutor vs executorservice
scheduledthreadpoolexecutor
scheduledexecutorservice
threadpoolexecutor java 8
threadpoolexecutor shutdown
threadpoolexecutor android
thread pool implementation in java

I have a ThreadPoolExecutor with one thread that will be used for batch processing, So before assigning a new task to the executor i have to wait for the earlier task to complete, i was doing this by depending upon the value for active jobs, but seeing in detail i found that, the executor doesn't executes the task instantly.

The problem this is causing to me is that i am ready to give the next batch but the first task has not yet started thus the value of active jobs is 0.

How can i get to run the task instantly. I am also OK with any other executor or way that this can be done.


You should probably use submit method from ExecutorService to schedule your tasks. Here is a working program that uses single thread executor to run 10 tasks. I casted to ThreadPoolExecutor to monitor thread pool state. You can wait for a single task by calling get on its corresponding Future instance or wait for all the tasks by invoking awaitTermination. If you don't need result from the Future just use Void. Hope it helps.

public class Main {                                                                                                                             
    static class TimingCallable implements Callable<Long> {                                                                                     
        static int MIN_WAIT = 200;                                                                                                              
        @Override                                                                                                                               
        public Long call() {                                                                                                                    
            long start = System.currentTimeMillis();                                                                                            
            try {                                                                                                                               
                Thread.sleep(MIN_WAIT + new Random().nextInt(300));                                                                             
            } catch (InterruptedException e) {                                                                                                  
                //DO NOTHING                                                                                                                    
            }                                                                                                                                   
            return System.currentTimeMillis() - start;                                                                                          
        }                                                                                                                                       
    }                                                                                                                                           

    public static void main(String[] args) throws InterruptedException, ExecutionException {                                                    

        ExecutorService executor =  Executors.newFixedThreadPool(1);                                                                            
        @SuppressWarnings("unchecked")                                                                                                          
        Future<Long>[] futureResults = new Future[10];                                                                                          
        for(int i =0; i < futureResults.length; i++) {                                                                                          
            futureResults[i] = executor.submit(new TimingCallable());                                                                           
            System.out.println(String.format("ActiveCount after submitting %d tasks: ", i+1) + ((ThreadPoolExecutor)executor).getActiveCount());
            System.out.println(String.format("Queue size after submitting %d tasks: ", i+1) + ((ThreadPoolExecutor)executor).getQueue().size());
        }                                                                                                                                       
        Thread.sleep(2000);                                                                                                                     
        System.out.println("ActiveCount after 2 seconds: " + ((ThreadPoolExecutor)executor).getActiveCount());                                  
        System.out.println("Queue size after 2 seconds: " + ((ThreadPoolExecutor)executor).getQueue().size());                                  
        for(int i =0; i < futureResults.length; i++) {                                                                                          
            if (futureResults[i].isDone()) {                                                                                                    
                System.out.println(String.format("%d task is done with execution time: ", i) + futureResults[i].get());                         
            }                                                                                                                                   
        }                                                                                                               //Waiting for the last task to finish
        System.out.println("Waiting for the last task result: " + futureResults[9].get());
        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.SECONDS);                                  
    }                                                                                                                                           
}                                                                                                                                               

Java Thread Pool - ThreadPoolExecutor Example, If there are more tasks than threads, then tasks need to wait in a queue like structure ThreadPoolExecutor separates the task creation and its execution. shutdownNow(): This method shut downs the executor immediately. Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.


If you are having only one thread to execute just use LinkedQueue for storing jobs once thread is done with the execution then only it will pick another task.

ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1,1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>());

Also you can have different strategies if you restricting size

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html

Read Rejected tasks

ScheduledExecutorService, But when we are not interested in executing a task as soon as possible and want to execute a task after a period of time or do it periodically, we� ThreadPoolExecutor is a java concurrent API and has been introduced in JDK 1.5. ThreadPoolExecutor is a ExecutorService that executes submitted Runnable task. ThreadPoolExecutor is instantiated by passing core pool size, maximum pool size, idle thread alive time, time unit for alive time, BlockingQueue, ThreadFactory and RejectedExecutionHandler.


Single thread pool executor service

Apparently you want to run multiple tasks immediately but in the order submitted.

Quite easy: Use an executor service backed by a single thread. The executor buffers up the tasks while waiting on earlier ones to complete. With on a single thread in the thread pool, only one task at a time can be executed, so they will be done sequentially in the order submitted.

The Executors class provides a choice of a few different thread pools backing an executor service. You want Executors.newSingleThreadExecutor().

ExecutorService es = Executors.newSingleThreadExecutor() ;

Submit a series of Runnable or Callable objects. Each represents a task to be executed.

es.submit(  ( ) -> System.out.println( "Hello. " + Instant.now() )  ) ;
es.submit(  ( ) -> System.out.println( "Bonjour. " + Instant.now() )  ) ;
es.submit(  ( ) -> System.out.println( "Aloha. " + Instant.now() )  ) ;
es.submit(  ( ) -> System.out.println( "Ciào. " + Instant.now() )  ) ;
es.submit(  ( ) -> System.out.println( "Shwmai. " + Instant.now() )  ) ;

Optionally, you can capture the Future object returned by each call to submit if you want to track completion of the tasks. (not shown in code above)

See this code run live at IdeOne.com.

Hello. 2019-11-29T09:10:13.426987Z

Bonjour. 2019-11-29T09:10:13.472719Z

Aloha. 2019-11-29T09:10:13.473177Z

Ciào. 2019-11-29T09:10:13.473479Z

Shwmai. 2019-11-29T09:10:13.473974Z

ThreadPoolExecutor - Java Thread Pool Example, We can invoke shutdown() method to finish execution of all the submitted tasks and terminate the thread pool. If you want to schedule a task to run with delay or� ThreadPoolExecutor uses threads from a thread pool to execute tasks. Advantages you get by using thread pool are- Pooled thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks. Thread objects use a significant amount of memory.


ThreadPoolExecutor (Java Platform SE 8 ), An ExecutorService that executes each submitted task using one of possibly You probably want to prestart threads if you construct the pool with a Here, an attempt to queue a task will fail if no threads are immediately available to run it,� In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.


Finally Getting the Most out of the Java Thread Pool, By repeating this process every time we need to execute a task, we're ExecutorService with methods for scheduling the execution of a task. I've given concurrent.futures.ThreadPoolExecutor a bunch of tasks, and I want to wait until they're all completed before proceeding with the flow. How can I do that, without having to save all the


Java Concurrency: Understanding Thread Pool and Executors, Single-threaded pool: keeps only one thread executing one task at a Consider using this executor if you want to schedule tasks to execute� I am using a ThreadPoolExecutor to execute tasks in my Java application. I have a requirement where I want to get the number of active tasks in the queue at any point in time in the executor queue . I looked up at the javadoc for ThreadPoolExecutor and found two relevant methods: getTaskCount() and getCompletedTaskCount().