Using ExecutorService class from java.util.concurrent package

Dear java programmers,
I have a question regarding the ExecutorService class from java.util.concurrent package.
I want to parse hundreds of files and for this purpose I'm implementing a thread pool. The way I use the ExecutorService class is summarized below:
ExecutorService executor = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++){
            System.out.println("Parsing file No "+i);
            executor.submit(new Dock(i));
        executor.shutdown();
        try {
            executor.awaitTermination(30, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        executor.shutdownNow();However, the code snippet above creates all the 1000 threads (Dock objects) at once and loads them to the executor, and thus I'm worrying about memory leak. I haven't tested it on 1000 files yet but just on 50 small ones, and even if the program prints out "Parsing file No "+i 50 times at once, it executes normally the threads in the background.
I guess the write way would be to keep the number of active/idle threads in the executor constant (lets say 20 if the thread pool's size is 10) and submit a new one whenever a thread has been finished or terminated. But for this to happen the program should be notified someway whenever a thread is done. Can anybody help me do that?
thanks in advance,
Tom

Ok I found a feasible solution myself although I'm not sure if this is the optimum.
Here's what I did:
        ExecutorService executor = Executors.newFixedThreadPool(10);
        Future<String> future0, future1, future2, future3, future4, future5, future6, future7, future8, future9;
        Future[] futureArray = {future0 = null, future1 = null, future2 = null, future3 = null, future4 = null, future5 = null,
        future6 = null, future7 = null, future8 = null, future9 = null};
        for (int i = 0; i < 10; i++){
            futureArray[i] = executor.submit(new Dock(i));
        }I created the ExecutorService object which encapsulates the thread pool and then created 10 Future objects (java.util.concurrent.Future) and added them into an Array.
For java.util.concurrent.Future and Callable Interface usage refer to:
[http://www.swingwiki.org/best:use_worker_thread_for_long_operations]
[http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/concurrencyTools.html]
I used a Future[] Array to make the code neater. So after that I submitted -and in this way filled up- the first 10 threads to the thread pool.
        int i = 9;
        while (i < 1000){
            for (int j = 0; j < 10; j++){
                if (futureArray[j].isDone() && i < 999){
                    try{
                        i++;
                        futureArray[j] = executor.submit(new Dock(i));
                    } catch (ExecutionException ex) {
                        ex.printStackTrace();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
            try {
                Thread.sleep(100); // wait a while
            } catch(InterruptedException iex) { /* ignore */ }
        executor.shutdown();
        try {
            executor.awaitTermination(60, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        executor.shutdownNow();
    }Each of the future[0-9] objects represents a thread in the thread pool. So essentially I'm check which of these 10 threads has been finished (using the java.util.concurrent.Future.isDone() method) and if yes I replenish that empty future[0-9] object with a new one.

Similar Messages

  • Getting problem with the new java.util.concurrent package

    i m using the new concurrency package of jdk 1.5 in my code. see the line:
    Executor threadPool = Executors.newCachedThreadPool();
    about this, api doc says Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available
    but i dont find this method to create new threads whenever required. please tell me about this.
    in my code, in some rare cases many threads r created, and very difficult to detect the number of active threads.
    as the previous one failed i tried with another one newFixedThreadPool(int). but here i got another problem. it works successfully but i dont understand what should be the size of the pool. i tried with 1000, it works well, but in a very rare case, it failed also. then i tried with 10000. but i m still confused, i dont know whether it would work always or not. with traditional threads my code never fails.
    please tell me, what should be the size of the pool and also let me know what is the problem with the first one (newCachedThreadPool)

    The thread pool should not be more than 100 threads. Ideally you should only have a small number of threads per CPU. If your threads are not long running it is possible that you could add 10,000 runnables but on start a small number of threads. Note, adding a thread take a non trivial amount of time so while the thread is added, all the others could finish. This could mean the number of threads could be 140 or smaller.
    Have you looked at the code to see what it does?

  • Java.util.concurrent.ConcurrentHashMap

    All,
    I prefer to use the java.util.ConcurrentHashMap over a Hashtable but there are some points regarding this structure that are not very clear to me.
    From java.util.concurrent: Class ConcurrentHashMap:
    "A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable.
    *+However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details. Iterators are designed to be used by only one thread at a time."+ *
    Also from: Java API: Package java.util.concurrent, we read:
    "The "Concurrent" prefix used with some classes in this package is a shorthand indicating several differences from similar "synchronized" classes. For example java.util.Hashtable and Collections.synchronizedMap(new HashMap()) are synchronized. But ConcurrentHashMap is "concurrent". A concurrent collection is thread-safe, but not governed by a single exclusion lock. In the particular case of ConcurrentHashMap, it safely permits any number of concurrent reads as well as a tunable number of concurrent writes. "Synchronized" classes can be useful when you need to prevent all access to a collection via a single lock, at the expense of poorer scalability. In other cases in which multiple threads are expected to access a common collection, "concurrent" versions are normally preferable. And unsynchronized collections are preferable when either collections are unshared, or are accessible only when holding other locks."
    Based on above, is this correct of I say:
    When using a structure like Hashtable, all the methods or operations are synchronized,
    meaning if one thread is accessing the Hashtable (by get(), put(),... or other methods on this structure), it owns the lock and all other threads will lock out until the thread that owns the lock releases the lock; which means only one thread can access the hash table at a time; which can cause performance issues.
    We need to use a synchronized block or method only of two threads modify a "shared resource", if they do not modify a shared resource, we do not need to use the synchronization.
    On the other hand, the methods of ConcurrentHashMap are not synchronized; so multiple threads can access the ConcurrentHashMap at the same time. But isn't the ConcurrentHashMap itself the "shared resource" that threads are accessing? Should we use it only if the threads are reading from map and not writing to it? And then if threads also write to the structure, then it looks like its better to not to use the ConcurrentHashMap, rather use the regular HashMap with the synchronized wrapper?
    Any help is greatly appreciated.

    We need to use a synchronized block or method only of two threads modify a "shared resource", if they do not modify a shared resource, we do not need to use the synchronization. Actually, you need to synchronize access to the shared resource for both readers and writers. If one thread is updating an unsynchronized HashMap, and a concurrent thread tries to read that map, it may be in an inconsistent state. When synchronizing on the map, the reader will be blocked until the writer completes.
    What you don't need to do is prevent multiple readers from accessing the map, if there's no writer. However, a synchronized map or HashTable will single-thread reads as well as writes.
    On the other hand, the methods of ConcurrentHashMap are not synchronized; so multiple threads can access the ConcurrentHashMap at the same time. But isn't the ConcurrentHashMap itself the "shared resource" that threads are accessing? No, it's actually synchronized at a finer level. Without getting into the details of HashMap implementation, an object's hashcode is used to identify a linked list of hashmap entries. The only time that you have a concurrency issue is when a reader and writer are accessing the same list. So the ConcurrentHashMap locks only the list that's being updated, and allows readers (and writers!) to access the other bucket lists. Plus, it allows two readers to proceed concurrently.

  • Java.util.concurrent.ConcurrentLinkedQueue efficient?

    If I need to put, say, 2K-3K nodes in a second in a multi threaded environment, would ConcurrentLinkedQueue of java.util.concurrent package of java version1.5 be efficeint ? Or should I use something lese??
    Thanks in advance..

    my whole code is in java, I am listening to two multicast sockets, and receiveing messages. I am missing a few data when it peaks to 2K-3K in a second. to resolve this, I thought of putting everything I receive to a shared buffer before i do anything to these messages, and process them from later. so, I thought of using ConcurrentLinkedQueue as temp buffer.

  • Java.util.concurrent.XYZ and cloneable

    Hello!
    How come that collection classes in java.util.concurrent do not implement Cloneable?
    On 01.06.2004 there was a bug report on CopyOnWriteArraySet regarding this:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5055732
    However, on 02.06.2004 the cloneable support was removed from the JSR166 repository?!
    http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java?rev=1.48&content-type=text/vnd.viewcvs-markup
    Best regards,
    Thomas

    Hello!
    How come that collection classes in java.util.concurrent do not implement Cloneable?
    On 01.06.2004 there was a bug report on CopyOnWriteArraySet regarding this:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5055732
    However, on 02.06.2004 the cloneable support was removed from the JSR166 repository?!
    http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/ConcurrentHashMap.java?rev=1.48&content-type=text/vnd.viewcvs-markup
    Best regards,
    Thomas

  • Java.util.concurrent.ExecutorService inside J2EE Container

    I want to use the JDK 1.5 concurrency class ExecutorService for concurrent execution of data-access logic inside my oc4j web-application.
    I'm using the Factory Executors.newFixedThreadPool(6) for creating a thread-pool.
    I know that it's not a good practice to create new threads inside a j2ee container.
    Is there anything I have to think of or beware of??
    Perhaps anybody here has experience using the java.util.concurrent.Executor inside OC4J or an other j2ee container.
    Thanks, Harald

    Yes, I have used java.util.concurrent.Executor in weblogic 10 server.
    You can really improve the performance of the EJB application if you use the thread pool carefully with limited size say 100 threads, by creating a single instance of thread pool for the whole J2EE application.
    You have to control the life cycle of thread pool using the container's life cycle methods, create the thread pool only once and destroy every time you recycle your app.
    Good luck with the implementation :)

  • Java.util.concurrent.ExecutorService inside OC4J

    I want to use the JDK 1.5 concurrency class ExecutorService for concurrent execution of data-access logic inside my oc4j web-application. I'm using the Factory Executors.newFixedThreadPool(6) for creating a thread-pool.
    I know that it's not a good practice to create new threads inside a j2ee container.
    Is there anything I have to think of or beware of??
    Perhaps anybody here has experience using the java.util.concurrent.Executor inside OC4J.
    Thanks, Harald

    Yes, I have used java.util.concurrent.Executor in weblogic 10 server.
    You can really improve the performance of the EJB application if you use the thread pool carefully with limited size say 100 threads, by creating a single instance of thread pool for the whole J2EE application.
    You have to control the life cycle of thread pool using the container's life cycle methods, create the thread pool only once and destroy every time you recycle your app.
    Good luck with the implementation :)

  • Using List Class in java.awt / java.util ?

    have a program that:
    import java.util.*;
    List list = new LinkedList();
    list = new ArrayList();
    ... read a file and add elements to array
    use a static setter
    StaticGettersSetters.setArray(list);
    next program:
    import java.awt.*;
    public static java.util.List queryArray =
    StaticGettersSetters.getArray();
    If I don't define queryArray with the package and class, the compiler
    gives an error that the List class in java.awt is invalid for queryArray.
    If I import the util package, import java.util.*; , the compiler
    gives an error that the list class is ambiguous.
    Question:
    If you using a class that exists in multiple packages, is the above declaration of queryArray the only way to declare it ?
    Just curious...
    Thanks for your help,
    YAM-SSM

    So what you have to do is explicitly tell the compiler which one you really want by spelling out the fully-resolved class name:
    import java.awt.*;
    import java.sql.*;
    import java.util.*;
    public class ClashTest
        public static void main(String [] args)
            java.util.Date today    = new java.util.Date();
            java.util.List argsList = Arrays.asList(args);
            System.out.println(today);
            System.out.println(argsList);
    }No problems here. - MOD

  • Java.util.concurrent.ExecutorService question!!!

    HI,
    I'm working with java.util.concurrent.ExecutorService. I need to know: Is there a possibility to know that all executions are done, that there is nothing to execute?????
    All ideas are welcome!:)
    Thanks a lot!:)
    Best,
    Aram.

    If I understood If I will use maxpoolsize of 1 that will be like Executors.newSingleThreadPool()?????It will be like SingleThreadPool, except that you can supply your own queue, with its own queueing characteristics. Also, there is no need to use five question-marks; four will suffice.
    Your tasks will be executed in the order they are in in the queue; read the documentation for the queue you choose for details. "Priority" is not a built-in concept in Java. You must implement the Comparable interface so that the priority-queue can tell which task should be executed next.
    And what "second queue"? A given executor will execute tasks off one queue.
    M.

  • Modifying JAR file using java.util.jar package  over the network

    Hello,
    I am modifying a JAR file programmatically using java.util.jar package. The time taken to save the contents to a local disk is very less (around 1 sec) . When I tried modifying the JAR from a remote machine over the network (from mapped drive or shared folder of WIN NT), the time taken to save is 15-20 times more.
    I am recreating the whole JAR while modifying. Is there any way to improve the performance. Or is it possible to write only the changed files?
    Thanks,
    Prasad Y S.

    When you "update" a jar file, you must always recreate it from scratch.

  • Supplementing java.util.concurrent.TimeUnit with a Duration?

    Ever since the concurrency classes were introduced in Java 5 have I been wondering why they designed all the interfaces so clumsily with regards to specifying durations:
    every method that expects an amount of time needs 2 parameters, one for the value and one for the unit. IMHO that should have been just one value-object!
    So in my projects I'm using a class called "Duration" that encapsulates a long value together with a TimeUnit. http://www.neppert.com/duration/doc/index.html
    It has turned out to be extremely handy, because it adheres to the DRY rule: only once, usually when reading timeouts from UIs or properties files into Durations do I need to consider the value's unit.
    Now when a user tells me "I don't want to type in stupid milliseconds, I want minutes", it's just one place I have to change ;-)
    Would it be good to have such a class in the JDK?

    jiju wrote:
    check whether import java.util.concurrent.*; is workingAwesome.
    As for netbeans, I went and double checked to see if it is reading from the most updated folder of Java and it is.
    So as I said, I am totally lost as to why it's not working. Should I just downgrade to a lower version of Java? Although it would seem kinda weird to do something like this.

  • Java.util.concurrent.LinkedBlockingDeque: cannot find symbol

    Hello,
    I'm trying to use an existing java code into a JavaFX application. To do this, I copied all my sources into the fx project in Netbeans and I linked the needed libraries, but when I tried to compile all this, I got the following message:
    "cannot find symbol
    symbol : class LinkedBlockingDeque
    location: package java.util.concurrent
    import java.util.concurrent.LinkedBlockingDeque;"
    the problem is at that line: import java.util.concurrent.LinkedBlockingDeque;
    This is a native java class. Is it not supported in JavaFx? Is not java fully compatible with Fx? What's happening?
    Thank you in advance

    Please, create an issue on it with the detailed comments: [http://www.netbeans.org/issues/enter_bug.cgi?component=javafx|http://www.netbeans.org/issues/enter_bug.cgi?component=javafx]

  • Using word/excel from java (client or weblogic server)

    Hi everybody,
    i want to use excel / word functionality from java in two different variants:
    -> serverside
    -> clientside
    I tried the weblogic.comc and i got serveral classes but in the remote-package i got only a utitlity-class.
    My knowlege about COM is rather bad.
    Does anybody did this bevor and
    -> can say me, if it is correct, that i only got a utility-class (so how will i use it from the client ?!)
    -> has a example for using Excel / Word from Java in bea weblogic
    -> has a example for using Excel / Word directly in a client (not via rmi)
    Thanks
    Ciao
    Sven

    Sven, This is a really bad idea. Why don't you tell me
    what your trying to do and I wil surely give you a better alternative
    JRadecki
    "Sven Roesner" <[email protected]> wrote:
    >
    Hi everybody,
    i want to use excel / word functionality from java in two different variants:
    -> serverside
    -> clientside
    I tried the weblogic.comc and i got serveral classes but in the remote-package i got only a utitlity-class.
    My knowlege about COM is rather bad.
    Does anybody did this bevor and
    -> can say me, if it is correct, that i only got a utility-class (so how will i use it from the client ?!)
    -> has a example for using Excel / Word from Java in bea weblogic
    -> has a example for using Excel / Word directly in a client (not via rmi)
    Thanks
    Ciao
    Sven

  • FU Ant task failure: java.util.concurrent.ExecutionException: could not close client/server socket

    We sometimes see this failure intermitently when using the FlexUnit Ant task to run tests in a CI environment. The Ant task throws this exception:
    java.util.concurrent.ExecutionException: could not close client/server socket
    I have seen this for a while now, and still see it with the latest 4.1 RC versions.
    Here is the console output seen along with the above exception:
    FlexUnit player target: flash
    Validating task attributes ...
    Generating default values ...
    Using default working dir [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\Source\Flex]
    Using the following settings for the test run:
    FLEX_HOME: [C:\dev\vert-d3flxcmn32\302100.41.0.20110323122739_d3flxcmn32]
    haltonfailure: [false]
    headless: [false]
    display: [99]
    localTrusted: [true]
    player: [flash]
    port: [1024]
    swf: [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build\commons.formatter.tests.unit.sw f]
    timeout: [1800000ms]
    toDir: [C:\DJTE\commons.formatter_swc\d3flxcmn32\reports\xml]
    Setting up server process ...
    Entry  [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build] already  available in local trust file at  [C:\Users\user\AppData\Roaming\Macromedia\Flash  Player\#Security\FlashPlayerTrust\flexUnit.cfg].
    Executing 'rundll32' with arguments:
    'url.dll,FileProtocolHandler'
    'C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build\commons.formatter.tests.unit.swf '
    The ' characters around the executable and arguments are
    not part of the command.
    Starting server ...
    Opening server socket on port [1024].
    Waiting for client connection ...
    Client connected.
    Setting inbound buffer size to [262144] bytes.
    Receiving data ...
    Sending acknowledgement to player to start sending test data ...
    Stopping server ...
    End of test data reached, sending acknowledgement to player ...
    When the problem occurs, it is not always during the running of any particular test (that I am aware of). Recent runs where this failure was seen had the following number of tests executed (note: the total number that should be run is 45677): 18021, 18, 229.
    Here is a "good" run when the problem does not occur:
    Setting inbound buffer size to [262144] bytes.
    Receiving data ...
    Sending acknowledgement to player to start sending test data ...
    Stopping server ...
    End of test data reached, sending acknowledgement to player ...
    Closing client connection ...
    Closing server on port [1024] ...
    Analyzing reports ...
    Suite: com.formatters.help.TestGeographicSiteUrls
    Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec
    Suite: com.formatters.functionalUnitTest.testCases.TestNumericUDF
    Tests run: 13, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.071 sec
    Results :
    Tests run: 45,677, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 201.186 sec
    Has anyone else ran across this problem?
    Thanks,
    Trevor

    I am not sure if this information will help everyone, but here goes...
    For us, these problems with FlexUnit tests crashing the Flash Player appear to be related to couple of factors. Recently, we moved up from Flex 3.2 to Flex 4.1 as our development baseline.  Many people complained that their development environment (Flash Builder, etc.) was much more unstable.  Apparently, 4.1 produces SWFs that require more memory to run than 3.2 does?  Anyway, we still had Flash Player 10.1 as our runtime baseline.  Apparently, that version of the player was not as capable of running larger FlexUnit test SWFs, and would crash (as I posted months earlier).  I upgraded to the latest 10.3 standalone player versions, and the crashes have now ceased.  It would be nice to know exactly what was causing the crashes, but memory management (or lack of) is my best guess.
    So, if you are seeing these issues, try upgrading to the latest Flash Player version.
    Regards,
    Trevor

  • Cannot import java.util.concurrent.locks ... WHY?

    Why is Xcode unable to find the java.util.concurrent.locks package. The class browser knows it exists. For example the entry for the ReentrantLock class looks like this in the browser class window:
    ReentrantLock (java.util.concurrent.locks)
    Xcode knows about other java.util packages such as java.util.ResourceBundle which I have been accessed successfully in other parts of my projecgt.
    Here is a source file and the resulting compiler error:
    The source file:
    // Foo.java
    import java.util.ResourceBundle;
    import java.util.concurrent.locks;
    public class Foo { }
    The compiler error:
    compile:
    Compiling 2 source files to /Users/Terry/Desktop/JAVA/PROJECTS/Logic/bin
    /Users/Terry/Desktop/JAVA/PROJECTS/Logic/src/Foo.java:3: cannot find symbol
    symbol : class locks
    location: package java.util.concurrent
    import java.util.concurrent.locks;
    ^
    1 error
    BUILD FAILED
    Help or hints would be greatly appreciated!

    Well the reason to your problem is very simple... java.util.concurrent.locks is a package... Not a class.
    if you want to import a specific class, the class should be written at the end like you did for import java.util.ResourceBundle; but if you want to import a whole package you need to add the little star at the end :
    import java.util.concurrent.locks.*;
    Or else, you only import the class you need :
    import java.util.concurrent.locks.ReentrantLock;

Maybe you are looking for