Executor

I noticed that a application called "Executor" was listed in the Firewall section of the Security preferences. What does it do? What are the problems with blocking incoming connections on it?

Hi Bill Loubiere;
Read this thread.
Allan
Message was edited by: Allan Eckert

Similar Messages

  • Using a SwingWorker in an Executor class?

    Here's some code that works and does what I want but I don't know if its a good idea....
    I have a program that may run one of a couple dozen long operations. I want to bring up a progress dialog to show the user how these operations are coming along.
    I was using a swing worker every time I ran a long task but its a pain to make changes in so many different places. So I set up the approach below.
    import java.util.concurrent.Executor;
    import javax.swing.JOptionPane;
    import com.sun.java.help.impl.SwingWorker;
    * This class takes a long task as a Runnable and
    * runs it while showing a progress dialog
    public class MyExecutor implements Executor
         public void execute(Runnable r)
              final MySmallProgressWindow dialog;
              dialog = new MySmallProgressWindow();
              final Runnable fr = r;
              dialog.show("Testing Executor ") ;
              final SwingWorker worker = new SwingWorker()
                   public Object construct()
                        try
                            fr.run();
                       catch(Exception g)
                             System.err.println(g);
                             JOptionPane.showMessageDialog(null, "Error: " + g.toString(), "Error", JOptionPane.ERROR_MESSAGE);
                       finally
                            dialog.hide();
                            System.out.println("Clean up here in finally");
                       return null;
                   public void finished()
                           dialog.hide();
             worker.start();
    I call it this way
    MyExecutor execute = new MyExecutor();                   
    Runnable runnableCopy = new Runnable() {
    public void run() {
         someLongTask();
    execute.execute(runnableCopy);Comments?
    Message was edited by:
    legoqueen

    import javax.swing.*;
    public class MyApplet extends JApplet {
         public void init() {
              //init stuff here
         public void start() {
              //start stuff here
         public static void main(String[] args) {
              JFrame f = new JFrame();
              JApplet a = new MyApplet();
              f.getContentPane().add(a);
              f.setSize(600, 400);
              f.setVisible(true);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              a.init();
              a.start();
    }Excuse me, but is there a way to do this on Applet only instead of JApplet... I was told we need to use Applet only...

  • Thread Pool , Executors ...

    Sorry if i make a stupid post now, but i'm looking for a implementation of a Thread Pool using the latest 1.5 java.util.concurrent classes and i can't find anything serious. Any implementation or link to a tutorial should be vary helpful.
    Thnx

    but i'm looking
    for a implementation of a Thread Pool using
    the latest 1.5 java.util.concurrent classes and i
    can't find anything serious. Any implementation or
    link to a tutorial should be vary helpful.
    Thnxhere is an Example :
    import java.util.concurrent.*;
    public class UtilConcurrentTest {
    public static void main(String[] args) throws InterruptedException {
    int numThreads = 4;
    int numTasks = 20;
    ExecutorService service = Executors.newFixedThreadPool(numThreads);
    // do some tasks:
    for (int i = 0; i < numTasks; i++) {
    service.execute(new Task(i));
    service.shutdown();
    log("called shutdown()");
    boolean isTerminated = service.awaitTermination(60, TimeUnit.SECONDS);
    log("service terminated: " + isTerminated);
    public static void log(String msg) {
    System.out.println(System.currentTimeMillis() + "\t" + msg);
    private static class Task implements Runnable {
    private final int id;
    public Task(int id) {
    this.id = id;
    public void run() {
    log("begin:\t" + this);
    try { Thread.sleep(1000); } catch (InterruptedException e) {}
    log("end\t" + this);
    public String toString() {
    return "Task " + id + " in thread " + Thread.currentThread().getName();
    }

  • Thread pool executor problem

    When using a thread pool executor (java.util.concurrent.ThreadPoolExecutor) to limit the number of threads executing at a time, the number of threads running still exceeds the limit number.
    This is the code:
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 20, TimeUnit.SECONDS, new LinkedBlockingQueue());
    The number of tasks in my program are 4, so i always have 4 threads running, although i limited it to 3.
    Can anyone help me with this problem? Or can u propose another solution to limit the number of running threads? By the way, i also tried using a newFixedThreadPool() and got the same problem.
    Thx.

    The number of tasks in my program are 4, so i always
    have 4 threads running, although i limited it to 3.How do you know that there are 4 threads running? If you're generating a JVM thread dump, you're going to see threads that are used internally by the JVM.
    Here's a simple program that creates a fixed-size threadpool and runs jobs. It limits the number of concurrent threads to 3. Compare it to what you're doing, I'm sure that you'll find something different. Also, verify that you're not creating threads somewhere else in your program; all of the ThreadPoolExecutor threads will have names of the form "pool-X-thread-Y"
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    public class ThreadPoolTest {
        public static void main(String[] args) {
            ExecutorService pool = Executors.newFixedThreadPool(3);
            for (int ii = 0 ; ii < 10 ; ii++) {
                pool.execute(new MyRunnable());
            pool.shutdown();
        private static class MyRunnable implements Runnable {
            public void run() {
                log("running");
                try {
                    Thread.sleep(1000L);
                catch (InterruptedException e) {
                    log("interrupted");
            private void log(String msg) {
                System.err.println(
                        msg + " on " + Thread.currentThread().getName()
                        + " at " + System.currentTimeMillis());
    }

  • Help me regards perfomance:java.util.concurrent.Executors

    hi friends,
    I implemented the concurrent.Executors in my project. to tell my problem consider a program that insert 1000 data into oracle database.
    instead of inserting 1000 data as a single operations i created 5 threads using the concurrent API. and inserted 200 records per thread.
    when i analyse the time(in miliseconds) i got the following result,
    insert the 1000 records through a single thread thks 200 ms.
    when i use 5 threads it taks atlease 200 ms to a single thread.
    so every threads finished it in 200 or 210 ms. so both perfomance is equal.
    Buy i want to run the each thread in 200/5. time. then my perfomance will be improved.
    Can anybody help me.
    With regards Prince

    i think eventhough i use the seperate connection i
    got some lock on some object when my Statement(not
    PreparedStatement) executes the query(by some other
    threads) so all the threads taks almost same time to
    finish like ordinary operation. is't it. i want to
    speadup the operation. Three threads doing the same stuff taking five turns each:
    1
    2
    3
    1
    2
    3
    1
    2
    3
    1
    2
    3
    1
    2
    3
    Notice something? They all start and end at the same time.
    because in my company i am doing the process with
    80000 data. i taks 1 hour to complete all tasks. how
    can i minimize the time by using the threads?Find the bottleneck first.

  • Where I save Executor instance in MDB environment

    Hi,
    I've been doing some experiences with JMS and Message Driven Beans.
    I put in a queue messages and see how many MDB beans catch and treat the message. I've concluded that Glassfish creates many MDB beans and some are removed.
    My goal is control the flux of messages treatment. In other words i dont want instances of beans treat the message in a uncontrolled manner. For example if i have 10 messages in a queue and the Application Server is running on a machine with two cpu cores i want only two messages be treated each time.
    I thought in instantiating an Executor. The motif is MDB beans get Executor reference and send the message to the Executor. The Executor see what threads are available in Thread Pool and treat the message.
    But the difficulty is how I save the Executor instance. In a static variable? In a MBean? In a shared memory (if yes how?).
    Thanks in advance.

    most app servers let you control the size of the "pool" used for various bean types. a google query for "glassfish mdb pool size" looks like it's returning relevant results.

  • Questions on Executor

    I have two questions regarding Executor and any suggestion is appreciated.
    1) Suppose I create a thread pool, tp = new ThreadPoolExecutor(...) where core pool size is 2, maximum pool size is 10, and it uses an ArrayBlockingQueue.
    Suppose I have a Runnable A. I submit Runnable A and Runnable B to thread pool tp. The run() method of Runnable A, after layers of calls, sumits Runnable a, b, c to thread pool tp and waits for result. Same code patterns happen to Runnable B. Since the thread pool queue is FIFO, is it true that the Runnable a, b, c would be sitting in the queue waiting for Runnable A to complete but Runnable A can't complete because it is waiting for the result of Runnable a, b, c and therefore resulting in a deadlock?
    If so, is there a good way to resolve this and avoid the deadlock? I think it could be resolved if I use a SynchronousQueue instead but I don't really want an unbounded thread pool. How can I make it bounded?
    2) In addition, I want to be able to customize the Executor such that I would be able to submit a collection of runnables/callables and be able to specify the number of threads that will run these callables. For example, if I use a SynchronousQueue each runnable/callable would take up a thread and I don't want that.
    Thank you very much!
    Grace

    Ping!
    I'm looking for this functionality too. Anyone have a solution to either of these? One that came to mind is to wrap the login items in a script which detects if the LAN is available.

  • Thread Pool executor

    I run a set of java programs as a single process in solaris os. Those java programs make use of thread pool executor to process threads and it runs in an infinite loop for ever. Thread processing is done whenever data is populated in database from an external source. The issue is after 2 to 3 days of running the process, it gets slowed down in executing the threads and finally it stops executing. What may be the reason for this.....how to solve this......... or how to fine tune thread pool executor in java or how to make best use of it...........

    Hey folks.... Sorry its a typo in my e-mail. Sorry about that. I am pasting the actual code here.
    The problem again is that in the index function only FirstRunnable executes but not the SecondRunnable
    final public class Crawler {
        / create an instance of the ISSThreadPoolExecutor /
        private static ThreadPoolExecutor mythreadpoolexecutor = ThreadPoolExecutor.getInstance();
        / Constructor /
        / Index function /
        public void index( .... ) {
            :::::: code :::::::::
            // Execute this folder in a seperate thread.
            this.issthreadpoolexecutor.execute(new FirstRunnable(alpha, beta, gamma));
        / The Inner Class /
        class FirstRunnable implements Runnable {
            public FirstRunnable(int alpha, int beta, int gamma) {
            public void run() {
                            doSomething();
                            // Some other tasks and ...spawn of another thread.
                            issthreadpoolexecutor.execute(new SecondRunnable(a));
             // The Inner Class that Indexes the Folder
              class SecondRunnable implements Runnable {
                      private int ei;
                      public SecondRunnable ( int abc ) {
                            this.ei = abc;
                      public void run() {
                            doSomething ( ".....") ;
              } // End of SecondRunnable Class.
         } // End of FirstRunnable class.
    } // End of Crawler Class.

  • Executors.newSingleThreadScheduledExecutor() creating multiple threads?

    While examining a stack trace this morning, I found approximately 250 idle threads labelled "pool-4-thread-###", where ### ranged from 1 to 250 or so.
    I then traced pool-4-thread to a ScheduledExecutorService and underlying ThreadPoolExecutor object created via a call to Executors.newSingleThreadScheduledExecutor().
    There are two types of tasks scheduled on that instance of the Executor. The first is a task which runs twice a day. The second type is something that gets scheduled as the result of a user action, which may occur dozens of times a day.
    Under what conditions can a SingleThreadScheduledExecutor create and leave around multiple threads?
    Thanks in advance,
    Mike Benveniste

    If the thread never completes.
    It's either hanging, or, more likely, has an exit condition that's never being met. Or it's spawning processes that are not completing.
    Simply put a debug statement at the beginning and end of the thread so you can see when (and if) it's starting and stopping.
    You may want to use object.killProcess() prior to starting the next instance to force the previous instance to stop if it still exists.
    bcf

  • How to get ThreadLocal using executor?

    I am using CompletionService for my producer/consumer problem.
            ExecutorService executor = Executors.newFixedThreadPool(threadPollSize);
            CompletionService<List<SomeObect>> completionService = new ExecutorCompletionService<List<SomeObect>>(executor);Once the executor spawns mutiple Threads I submit the tasks..
    completionService.submit(new Callable<List<SomeObect>>()     {
                      public List<SomeObect> call() throws IngestSystemException {
                           FileConnector connector = ThreadLocalFtpConnectionUtil.getThreadLocalFileConnector(getConnector().getFtpCredentials().getServerName(),
                                     getConnector().getFtpCredentials().getUserName(),
                                     getConnector().getFtpCredentials().getPassword(),
                                     getConnector().getFtpCredentials().getRootDirectory());
                 Now ever Thread uses its own copy of FtpConnection...Hence ThreadLocal...Here is the ThreadLocal code
        private static ThreadLocal<FtpConnector> threadLocal = new ThreadLocal<FtpConnector>();
         * @param serverName
         * @param userName
         * @param password
         * @param rootDirectory
         * @return
        public static synchronized FtpConnector getThreadLocalFileConnector(String serverName, String userName,
                  String password, String rootDirectory) throws IngestSystemException {
             FtpConnector ftpConnector = null;
            if (threadLocal.get() == null) {
                 ftpConnector = new FtpConnectorImpl(
                           new FtpCredentials(serverName,userName,password,rootDirectory));
                try {
                     ftpConnector.open();
                }catch (FileConnectionException e){
                     throw new Exception(String.format("Exception opening ftp connection for" +
                               " server [%s]" +
                               " username [%s]" +
                               " password [%s]" +
                               " root directory [%s]",
                                    serverName,
                                    userName,
                                    password,
                                    rootDirectory),e);
                 threadLocal.set(ftpConnector);
            }else{
                 ftpConnector = threadLocal.get();
            return ftpConnector;
         * @return
        public static synchronized void closeConnection(){
             FtpConnector ftpConnection = null;
             try {
                  ftpConnection = threadLocal.get();
                  ftpConnection.close();
             }catch(FileConnectionException e){
                 throw new RuntimeException(String.format("Exception closing ftp connection for thread%s",Thread.currentThread()),e);
        }Everything works fine...My problem I need to close all the ftp connections held by ThreadLocal for every Thread spawned by the executor; only after the executor is done..possibly at shutdown()
    One option I got working is writing my own ThreadPoolExecutor and in this workerDone method I close the ftp connection.
         * Perform bookkeeping for a terminated worker thread.
         * @param w the worker
        void workerDone(Worker w) {
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                 // close all the Ftp connections
                 ThreadLocalFtpConnectionUtil.closeConnection();
        }But to get this to work I had to write my own RejectedExecutionHandler, ThreadPoolExecutor, and Executors.
    Is there any other way to solve this problem?
    Edited by: passtor on Oct 15, 2007 4:39 PM

    My problem I need to close all the ftp connections held by ThreadLocal for every Thread spawned by the executor; only after the executor is done..possibly at shutdown()Then you can't use ThreadLocal. ThreadLocal data can only be accessed by the thread that put it there.

  • Executors inside a container

    Hi. I need to use ExecutorService inside my application.
    Application is targeted to intensive usage and I want to take advantage of Java SE 5 concurrency.
    How can I use Executors inside Web container? Can I create ExecutorService and put it to ServletContext?
    How can I use Executors inside EJB container? Can I put it to JNDI?
    Is there any restrictions or special conditions to do this?

    Frank,
    Thanks, wasn't sure what extra information to provide but I'm running 11.1.1.3.0 of JDeveloper. If I create a two level tree data contol that works fine. When I add the third level I get the error yet I can navigate through the data control using the business components browser and the structure seems fine. I've tried two separate two level data controls; the first with the top two levels of the tree, the second with the bottom two levels of the tree. Both work fine but when I combine them into a single data control, then I get the error.
    One of the problems I have is not knowing what the error means, so I have no idea what to start looking at to determine what to do to try to remedy it.
    George

  • Multiple thread pools under single executor

    I would like to segregate the tasks running in an Executor so that certain tasks (perhaps identified by an annotation) could be restricted to a thread pool of a limited size while others run in a different pool.
    The intend is to limit certain crunchy tasks so that they don't saturate a limited resource.
    As far as I can tell I can't do this with a ThreadPoolExecutor even with a custom ThreadFactory. The original Callable is wrapped a couple of times by the time the ThreadFactory.newThread method is called so I can't inspect it at that time. Also, once the maximumPoolSize is reached the waiting tasks will get handed off to whichever thread finishes first, thus making my fixed pools useless.
    I have a feeling that I will need to write my own ThreadPoolExecutor but I thought that I would ask if there was a way to do this with the existing classes first.
    Thanks.

    I used to do this.
    The problem comes in managing the work that flows between the queues, and managing the results. I need to be able to take the output from one task and feed it into another, potentially running in a different thread pool.
    Multiple queues mean waiting for more than one blocking event, which means multiple management threads with a meta-event queue feeding back to an dispatcher that does the messaging.
    With multiple management threads you have to poison all of those queues so that the thing shuts down when you are done.
    By the time that I'm done I may be better off just modifyingThreadPoolExecutor to do what I want. One work queue keeps the shutdown problem under control.
    Thanks for the feedback.

  • Concurrency, Executors

    Hi Guys
    I have written this class to send mails off and it works perfecly except that it puts java.exe
    at 50% cpu usage permanently.
    Can anybody see a design flaw and point it out too me? I do not understand why this is clogging up the cpu?
    import java.io.File;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import ConnectionFactory;
    import ExceptionHandler;
    import .PortalSettings;
    public class MailSender implements Runnable {
        private ConnectionFactory factory;
        private PortalSettings settings;
        private Thread runner;
        private ExecutorService pool;
        private static final int MAX_THREADS = 10;
        public MailSender() {
        public MailSender(PortalSettings settings) {
            setSettings(settings);
            this.pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
            this.runner = new Thread(this);
            this.runner.setName("MailSender");
            this.runner.start();
         * @param factory the factory to set
        public void setFactory(ConnectionFactory factory) {
            this.factory = factory;
         * @param settings the settings to set
        public void setSettings(PortalSettings settings) {
            this.settings = settings;
            setFactory(new ConnectionFactory(settings));
        public void sendMail() throws Exception {
            try {
                Set<Future<Mail>> set = new HashSet<Future<Mail>>();
                Mail[] mails = new Mail(this.factory, this.settings).getAllForSend(new Date());
                for (Mail m : mails) {
                    System.out.println("SUBMITTING MAIL : " + m);
                    Future<Mail> future = pool.submit(m);
                    set.add(future);
                for (Future<Mail> future : set) {
                    System.out.println("BEFORE SENDING MAIL...");
                    Mail executedMail = future.get();
                    System.out.println("EXECUTED... RESULT : " + executedMail.getStatus());
                    if (executedMail.getStatus() != Mail.STATUS_SENT) {
                        //mail not sent notify users
                        System.out.println("Notify users that mail is not sent");
                        System.out.println("\t" + executedMail);
            } catch (Exception e) {
                ExceptionHandler.handleException(e);
        public void run() {
            while (this.runner == Thread.currentThread()) {
                try {
                    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t" + "Sending Mails");
                    long startTime = System.currentTimeMillis();
                    this.sendMail();
                    long endTime = System.currentTimeMillis();
                    long sleepTime = endTime - startTime;
                    System.out.println("Sleep Time (millis) = " + sleepTime);
                    if (sleepTime >= (1000*60)) {
                        System.out.println("Mail sending took longer than 1 minute");
                    } else {
                        Thread.sleep((1000*60) - sleepTime);
                } catch (Exception e) {
                    ExceptionHandler.handleException(e);
        public static void sendMail(ConnectionFactory factory, String subject, String fromAddress,
                String message, List<String> toAddresses,
                File... attachments) throws Exception {
            Mail mail = new Mail(factory);
            mail.setMailSubject(subject);
            mail.setMailBody(message);
            mail.setMailSendDate(new java.util.Date());
            mail.setStatus(Mail.STATUS_NOT_SENT);
            mail.setMailFromAddress(fromAddress);
            for (Iterator<String> it = toAddresses.iterator(); it.hasNext();) {
                mail.addMailToAddress(it.next());
            for (int i = 0; i < attachments.length; i++) {
                File file = attachments;
    mail.addMailAttachment(file);
    mail.save();

    Hi Guys
    I have written this class to send mails off and it works perfecly except that it puts java.exe
    at 50% cpu usage permanently.
    Can anybody see a design flaw and point it out too me? I do not understand why this is clogging up the cpu?
    import java.io.File;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import ConnectionFactory;
    import ExceptionHandler;
    import .PortalSettings;
    public class MailSender implements Runnable {
        private ConnectionFactory factory;
        private PortalSettings settings;
        private Thread runner;
        private ExecutorService pool;
        private static final int MAX_THREADS = 10;
        public MailSender() {
        public MailSender(PortalSettings settings) {
            setSettings(settings);
            this.pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
            this.runner = new Thread(this);
            this.runner.setName("MailSender");
            this.runner.start();
         * @param factory the factory to set
        public void setFactory(ConnectionFactory factory) {
            this.factory = factory;
         * @param settings the settings to set
        public void setSettings(PortalSettings settings) {
            this.settings = settings;
            setFactory(new ConnectionFactory(settings));
        public void sendMail() throws Exception {
            try {
                Set<Future<Mail>> set = new HashSet<Future<Mail>>();
                Mail[] mails = new Mail(this.factory, this.settings).getAllForSend(new Date());
                for (Mail m : mails) {
                    System.out.println("SUBMITTING MAIL : " + m);
                    Future<Mail> future = pool.submit(m);
                    set.add(future);
                for (Future<Mail> future : set) {
                    System.out.println("BEFORE SENDING MAIL...");
                    Mail executedMail = future.get();
                    System.out.println("EXECUTED... RESULT : " + executedMail.getStatus());
                    if (executedMail.getStatus() != Mail.STATUS_SENT) {
                        //mail not sent notify users
                        System.out.println("Notify users that mail is not sent");
                        System.out.println("\t" + executedMail);
            } catch (Exception e) {
                ExceptionHandler.handleException(e);
        public void run() {
            while (this.runner == Thread.currentThread()) {
                try {
                    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t" + "Sending Mails");
                    long startTime = System.currentTimeMillis();
                    this.sendMail();
                    long endTime = System.currentTimeMillis();
                    long sleepTime = endTime - startTime;
                    System.out.println("Sleep Time (millis) = " + sleepTime);
                    if (sleepTime >= (1000*60)) {
                        System.out.println("Mail sending took longer than 1 minute");
                    } else {
                        Thread.sleep((1000*60) - sleepTime);
                } catch (Exception e) {
                    ExceptionHandler.handleException(e);
        public static void sendMail(ConnectionFactory factory, String subject, String fromAddress,
                String message, List<String> toAddresses,
                File... attachments) throws Exception {
            Mail mail = new Mail(factory);
            mail.setMailSubject(subject);
            mail.setMailBody(message);
            mail.setMailSendDate(new java.util.Date());
            mail.setStatus(Mail.STATUS_NOT_SENT);
            mail.setMailFromAddress(fromAddress);
            for (Iterator<String> it = toAddresses.iterator(); it.hasNext();) {
                mail.addMailToAddress(it.next());
            for (int i = 0; i < attachments.length; i++) {
                File file = attachments;
    mail.addMailAttachment(file);
    mail.save();

  • Identifying the Runnable initiated by Executor

    Im trying out the Executor classes in java 1.5, constructing a pool of them with
      Executors.newFixedThreadPool(THREAD_POOL_SIZE);it is used to create whenever I need to invoke a Runnable() object
    I have also used
    Thread.Thread.setDefaultUncaughtExceptionHandler() to set a defaultexceptioon handler for uncaught exceptions.My question is how does the exceptionhandler identify which Runnable class is being run by the thread ?
    Before I used Executor I would construct every Thread with a name from the Runnable() object I was invoking but with Executor you cannot specify a threadname (because It want to reuse a thread....) so how can I track back to the Runnable type.

    OK, thanks Thread.currentThread().setName() does the
    trick, does it matter if I dont set it back ?Not if you control all the tasks using the executor. It is only informational.
    I will explain a bit more in case Im doing something
    I shouldnt be, the application is a Swing Gui
    application so whenever I want to run a task that may
    take some time I run it within a seperate Thread (so
    it isnt tying up the EventDispatchThread). A
    particular task will only be invoked by one Thread at
    any time , for example I have a loadFromFile() task,
    there will never be multiple loadFromFile() tasks
    running concurrently so I feel safe to set the Thread
    name based on the Runnable classes name.Sounds like a SingleThreadedExecutor will do the job - which is only slightly different to a fixed pool of size 1. (The former always has 1 thread, the latter can be changed later.)
    I was looking at The ExecutorService as a means to
    reducing Thread allocation costs, because most of the
    Threads are short living.Sure. If there is only one active task you just need one thread in the executor. It will get replaced if the task throws exceptions.

  • Optimization of Thread Pool Executor

    Hi,
    I am using ThreadPoolexecutor by replacing it with legacy Thread.
    I have created executor as below:
    pool = new ThreadPoolExecutor(coreSize, size, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(coreSize), new CustomThreadFactory(name),new CustomRejectionExecutionHandler());
           pool.prestartAllCoreThreads();
    here core size is maxpoolsize/5
    and i have prestarted all the core threads on start up of application roughly around 160 threads.
    in legacy design we were creating and starting around 670 threads.
    But the point is even after using Executor and creating and replacing  legacy design we are not getting much better results.
    For results memory management we are using top command to see memory usage
    and for time we have placed loggers of System.currentTime in millis to check the usage.
    Please tell how to optimize this design
    Thanks & Regards,
    tushar

    The first step is to decide what you want to optimize. I'm guessing you want to minimize the total elapsed time for the job to run, but anyway that's your first step. Determine what you're optimizing. Then measure the performance of the job, with respect to that metric, for various pool sizes, and see what happens.
    However I'm not sure why you expected that rewriting the application to use the ThreadPoolExecutor would improve the runtime performance of the job. I would expect it might simplify the code and make it easier for future programmers to understand, but it's possible that your thread pool implementation performs just as well.

  • Exceptions in Executor.submit

    Run the following test code:
    public class Test {
        public static void main(String[] args) {
            ExecutorService executor = Executors.newCachedThreadPool();
            executor.submit(new Runnable() {
                public void run() {
                    throw new RuntimeException("This is a runtime exception");
    }Why doesn't the stack trace show up on System.out as it would normally do if I had executed the runnable in a new Thread? Is there anyway short of wrapping the whole run method in a try-catch block of getting that stack trace.
    TIA.

    When you submit your Runnable to the ExecutorService you get a Future back. Calling get() on that Future will result in an ExecutionException being thrown. The cause of that exception is your RuntimeException:
    import java.util.concurrent.*;
    public class Test {
        public static void main(String[] args) {
            ExecutorService executor = Executors.newCachedThreadPool();
            Future<?> f = executor.submit(new Runnable() {
                public void run() {
                    throw new RuntimeException("This is a runtime exception");
            try {
                f.get();
            catch (Exception e) {
                e.printStackTrace();
    }I've recently started to play around with these things myself, and here is my understanding of it:
    An ExecutorService uses a FutureTask by default when you submit a Runnable (see the source code for AbstractExecutorService). That FutureTask basically wraps your Runnable inside atry { ... } catch (Throwable) {... }which explains why your exception doesn't slip through. Instead, the throwable is stored inside the FutureTask. When you call get() on the Future, the throwable is wrapped inside an ExecutionException, as described above.

Maybe you are looking for

  • Determine BADI from Enterprise Web Service?

    Hi all, We've just started to work with Enterprise Web Services and have a need to enhance one of them.  Using ES Workplace we have identified the 'Read Purchase Order' as a candidate and want to see what capabilities exist in making minor changes. 

  • Withholding Tax Sections not displaying in  Withholding tax allowed window!

    Dear All, I have got withholding tax issue after upgrading 2007B to 8.81 PL:09 U know,On BP master data-Accounting-Tax-Withholding tax allowed,where we choose type of section to be selected but sections are not coming in Withholding tax allowed windo

  • IPhoto 6 roll feature is all messed up

    I'm running 10.4.10, Mac Pro, all latest OS and application patches applied. iPhoto is version 6.0.6, and I have 10,584 pictures in my library. With the background out the way, here's the problem: the "Rolls" feature seems to be completely out of wha

  • How to install struts application in a real web server

    I have a problem about installing my struts application into web server.. I can run my application under eclipse websphere development studio 5.0 web server but I don't know How I install it a real webserver (Apche,Unix,Tomcat or etc.) under location

  • Passing page_url using hyperlink

    Hi, I would like to pass the page_url of the show_edit_mode to other procedures that I am calling using hyperlink(anchor tag). This works fine if I am using hidden variables & submitting the page. But if I am passing it as an argument of the hyperlin