mercredi 6 mai 2015

How can I improve/optimize my program with ExecutorService?

So, I'm new in Java.

I wrote relatively simple program that does something with a lot of files.

It was slow, I wanted to run more threads than one. With little StackOverflow Community help I made something like this:

public class FileProcessor {
    public static void main(String[] args)
    {
        // run 5 threads
        ExecutorService executor = Executors.newFixedThreadPool(5);
        int i;

        // get first and last file ID to process
        int start = Integer.parseInt(args[0]);
        int end = Integer.parseInt(args[1]);

        for (i = start; i < end; i++)
        {
            final int finalId = i; // final necessary in anonymous class
            executor.submit(new Runnable() 
            {
                public void run() 
                {
                    processFile(finalId);
                }
            });
        }
    }

    public static void processFile(int id)
    {
        //doing work here
    }
}

This is really really simple multithreading solution and it does what I want. Now I want to improve it.

  1. Shall I reduce number of Runnable objects existing in memory at the same time? If I should - how can I do it?

  2. How can I detect, that all job is done and exit program (and threads)?

Aucun commentaire:

Enregistrer un commentaire