Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executor service in java--> how to convert single thread code to use executor

Pardon me if the question sounds silly - I am just starting to use Executor.

I have an existing java app that uses threads in this manner-- basically standalone threads are used--

private Thread spawnThread( )
    {

        Thread t = new Thread()
        {
            String taskSnap = task.toString();
            public void run()
            {
                try
                {
                    println( task.run( null ) );
                }catch( InterruptedException e )
                {
                    println( "ITC - " + taskSnap + " interrupted " );
                }
            }
        };
        return t;
    }

As you can see from above, the function returns a new thread.

Now in the main() function of the program, a new thread is created in this manner--

    taskThread = spawnThread();

    taskThread.start();

What i want to do is, create an executor service (with fixed number of threads)--> and then hand off creation of new thread/execution of task by the new thread to that executor.

As I am very new to Executor, what I wish to know is, how do I change the above code so that instead of a new separate thread being formed, a new thread is instead created within the thread pool. I cannot see any command to create a thread (within the thread pool)--> hand off the above task to that thread (and not to a stand-alone thread as above).

Please let me know how to resolve this problem.

like image 509
Arvind Avatar asked Feb 17 '13 06:02

Arvind


People also ask

What is single threaded Executor?

Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.)

How do I make sure only one thread is running in Java?

Use java. util. concurrent. Semaphore with number of thread equals 1, so only 1 thread at an time instance can access that resource.

How do you create an Executor service thread?

We use the Executors. newSingleThreadExecutor() method to create an ExecutorService that uses a single worker thread for executing tasks. If a task is submitted for execution and the thread is currently busy executing another task, then the new task will wait in a queue until the thread is free to execute it.


3 Answers

In your main, you can write something like this:

ExecutorService executor = Executors.newFixedThreadPool(nThreads);
executor.submit(new Runnable() {
    String taskSnap = task.toString();
    public void run() {
            try {
                println(task.run(null));
            } catch( InterruptedException e) {
                println("ITC - " + taskSnap + " interrupted ");
            }
    }
});

The submit method will execute the Runnable on one of the threads within the executor service.

Note: Don't forget to shutdown the executor service when you don't need it any more or it will prevent your program from exiting.

like image 186
assylias Avatar answered Nov 05 '22 18:11

assylias


Do your research before asking. The idea is to create a class which implements Runnable and execute it using executor service.

Example from: Java Concurrency (Multithreading) - Tutorial

Implementation of the worker (which implements Runnable):

package de.vogella.concurrency.threadpools;

/** * MyRunnable will count the sum of the number from 1 to the parameter * countUntil and then write the result to the console. * <p> * MyRunnable is the task which will be performed * * @author Lars Vogel * */

public class MyRunnable implements Runnable {
  private final long countUntil;

  MyRunnable(long countUntil) {
    this.countUntil = countUntil;
  }

  @Override
  public void run() {
    long sum = 0;
    for (long i = 1; i < countUntil; i++) {
      sum += i;
    }
    System.out.println(sum);
  }
} 

How to use executor service to run trigger the worker thread.

package de.vogella.concurrency.threadpools;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
  private static final int NTHREDS = 10;

  public static void main(String[] args) {
    //You can also use Executors.newSingleThreadExecutor() if you just need 1 thread
    ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
    for (int i = 0; i < 500; i++) {
      Runnable worker = new MyRunnable(10000000L + i);
      executor.execute(worker);
    }
    // This will make the executor accept no new threads
    // and finish all existing threads in the queue.
    executor.shutdown();
    // Wait until all threads are finish
    //while (!executor.isTerminated()) {
    //}
    //System.out.println("Finished all threads");
    //All the threads might not be finished at this point of time. Thread endtime purely depends on the time taken by the processing logic inside your thread.
  }
} 
like image 42
zengr Avatar answered Nov 05 '22 20:11

zengr


You mean something like this?

class Parallel {
    private ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    public void shutdown() {
        pool.shutdown();
    }

    public void foo() {
        pool.submit(new Runnable() {
            @Override
            public void run() {
                // put your code here
            }
        });
    }
}
like image 22
Axel Avatar answered Nov 05 '22 20:11

Axel