TIme taken by Child threads to execute

Hi
I have a small query related to multithreading. I have a main thread launching a few Child threads. Now I want to check how much time all the 10000 child threads are taking to execute. I cannot write a System.currentTimeMillis(); before a main thread exits because I want the Child threads to keep executing even after the Main thread exits because I do not know how much time the child threads will take. I have made the child threads as non-deamon
class ChildThread implements Runnable {
     Thread t;
     int i;
     ChildThread(int i) {
          t = new Thread(this, "SMS Thread");
          this.i = i;
          t.setDaemon(false);
          t.start();
     public void run() {
          try {
               System.out.println(i);
          } catch (Exception smsex) {
               System.out.println("Exception occured while sending message :"
                         + smsex.getMessage());
               smsex.printStackTrace();
public class MainThread {
     public static void main(String args[]) {
          long start = System.currentTimeMillis();
          ChildThread thread = null;
          try {
               for (int i = 10000; i > 0; i--) {
                    thread = new ChildThread(i); // create a new thread
          } catch (Exception e) {
               System.out.println("Main thread interrupted.");
          long end = System.currentTimeMillis();
          System.out.println("Main thread exiting. Took " + (end - start)
                    + " ms.");
}

This is a sample i have assumed.. dont have the complete code.
I will just explain this
Create an executor service object in a class called ThreadDispatcher.
And create your chileThread as given below
class ChildThread implements Runnable {
     ChildThread() {                    
     public void run() {
          try {
               System.out.println(i);
          } catch (Exception smsex) {
               System.out.println("Exception occured while sending message :"
                         + smsex.getMessage());
               smsex.printStackTrace();
}And the ThreadDispatcher class as below -This is just to beautify the code :)
public class ThreadUtil {
private static ExecutorService exec = Executors.newFixedThreadPool(some_value);
public static List<Future> executionResults = new ArrayList<Future>();
}And finaly come to the main Thread class
public class MainThread {
     public static void main(String args[]) {
          ChildThread thread = null;
          try {
                         long start = System.currentTimeMillis();
               for (int i = 10000; i > 0; i--) {
                    thread = new ChildThread(i); // create a new thread
                                ThreadDispatcher.executionResults.add(ThreadDispatcher.exec.submit(thread));
          } catch (Exception e) {
               System.out.println("Main thread interrupted.");
                //Here place the while loop to check each thread status
                 while (ThreadDispatcher.executionResults.size() > 0) {
               try {
                    Future task = ThreadDispatcher.executionResults.get(0);
                    task.get();//Wait until the thread finishes execution
                                ThreadDispatcher.executionResults.remove(task);
               } catch (InterruptedException e) {
                    e.printStackTrace();
               } catch (ExecutionException e) {
                    e.printStackTrace();
          long end = System.currentTimeMillis(); //This time will probably be the end time.
          System.out.println("Main thread exiting. Took " + (end - start)
                    + " ms.");
}Hope this will be helpful...

Similar Messages

  • Time taken for a method to run. ?

    I have a query regarding ascertaining the time taken
    for a method to execute
    I have a SQL statement that I reads 10,000 rows.
    String a_SQL = "Select.....from TableA";
    try {
         IQuery query = m_UC.createQuery();
         SimpleTableModel stm = query.executeSelect(a_SQL);
       }catch(SQLException se){
       // Query Over.
       private void displayJTable(){
       // display rows read from the query above.
       }          As the query is executing,I want to display a progress bar
    showing the status of the query.
    Now I cant use this :
    start = System.currentTimeMillis();
    try {
         IQuery query = m_UC.createQuery();
         SimpleTableModel stm = query.executeSelect(a_SQL);
       }catch(SQLException se){
    end = System.currentTimeMillis();
    System.out.println(" Time taken  to display " + (end - start)/1000);
                  The above will give me the time elapsed in seconds for the SQL query to execute,but
    this is not what I want.
    What i want is to use this :
           // Progress BAR executing,so I need to get to know the time
           // taken for the query to run
            try {
            the SQL execution
            }cach(){
            // Query over.
            // Stop Progres Bar.
            // Display JTable.       How can I know when to stop the Progress Bar as I have no handle
    on the time taken to execute the query?
    Any help will be appreciated

    You can have a separate thread (or maybe it's just part of the regular GUI update thread? I don't know details about GUIs) that puts up an hourglass or spinning clock hands or dancing hamster or whatever to indicate that something is going on, but like the man says, you can't know ahead of time how long it will take to run a query, so you can't show percent done. You also don't in general know ahead of time how many rows will be returned so that doesn't help you.
    You might be able to do something for the processing of the returned data, once the query completes, because then you can often get a count of the number of rows, so you process each row in a loop, and update the % done counter each time through the loop.

  • Exceptions in child thread

    Hello,
    I am writing a few classes that i plan on reusing a lot. The classes create
    child threads that do ... work. If a exception is cought in one of the child threads
    I want to send it up to the caller. I can't declare the run() method of a thread to throw
    an exception ... so could someone suggest a nice clean way to get the cought exception back to the caller.
    Thanks,
    jd

    To answer that question, you need to think about what the "caller" (the parent thread) is doing while the child thread is executing.
    Is it waiting in a join() call?
    Is it doing its own processing?
    What do you expect it to do when a child thread throws an exception?
    (The answer to the bolded questions may drive how you report the exception back to the parent thread.)
    With a typical single-threaded chain of calls, when an exception is encountered, there is a well defined stack back to the main() method--main called foo which called bar which called baz, etc. In a multithreaded context, the parent thread could potentially be executing any of its instructions when the exception occurs. Remember, the parent thread and child thread are executing independently of each other.

  • How to analyse the time taken for a query

    Hey gurus ,
                          How to find the time taken for a query to execute .
    Regards,
    Venkatesh

    Hi,
    Time taken to execute a query = FRONT END TIME + OLAP TIME + DB TIME.
    front end time is time taken to do format in BEX.
    olap time is time taken to aggegate data in OLAP buffer.
    db time is tme taken to collect data at data target.
    to fine all these information
    goto RSRT -> give query name -> execute+debug -> it will display all the fields > check fields what ever u want.
    Regards,
    Haritha.

  • Time taken to execute my report?

    Hi Expects,
    I want to print in the output how much time taken to execute my report. Please help on this.
    regards,
    vijay

    Hi vijay,
    1. simple
    2. we have to use two things to get Current time.
       GET TIME
       SY-UZEIT.
    3.
    report abc.
    data : t1 type sy-uzeit.
    data : t2 type sy-uzeit.
    data : diff type i.
    data : ekko like table of ekko with header line.
    get time.
    t1 = sy-uzeit.
    select * from ekko into table ekko.
    select * from ekko into table ekko.
    get time.
    t2 = sy-uzeit.
    write :/ t1.
    write :/ t2.
    diff = t2 - t1.
    write :/ 'Time Taken : ' , diff.
    regards,
    amit m.

  • How to identify time taken to execute a package

    Hi all,
    Is the method without TKPROFF to find the time taken to execute a package that calls a procedure.
    for examples
    Lets says I execute a packaage at SQLplus window
    SQL> Execute my_pack.bal_proc;
    (It took some time may be 4 hrs to excecute according to my watch).
    At this stage if I want to find the time by some sql command that after executing the package what was the time.
    can someone help me in finding a query that tell what was the time taken to execute a package.
    thanks n rgds
    saaz

    You can check start and end time
    Then end time -start time
    SQL> select systimestamp start_time from dual;
    START_TIME
    11-AUG-09 11.30.47.758282 AM -04:00
    SQL> Execute my_pack.bal_proc;
    SQL> select systimestamp end_time from dual;
    END_TIME
    11-AUG-09 11.31.11.207530 AM -04:00Edited by: user5495111 on Aug 11, 2009 8:32 AM

  • Time taken to execute code vs time taken to render to screen....

    Hello Experts,
    I noticed something strange while debugging some of my code.
    I have a for loop in which I'm creating and adding node elements. Above the for loop I'm creating a modal window, and after the for loop I'm destroying the modal window. In the modal window I have a timedtrigger element with a delay of one second.
    Here is the pseudocode:
    createModalWindow();
    for(int i=0; i<200; i++)
        // create and add node elements
    destroyModalWindow();
    Inside the modal windows wdDoInit() method I enable the timedTrigger, inside the wdDoExit() method, I disable the timedTrigger.
    When I execute this code I get a null pointer exception because the application is trying to destroy a window instance that doesn't exist!!! ie the modal window. When I comment out the destroyModalWindow() line, I noticed that the modal window get rendered after the loop has finished its processing not before like I'd expect. Could this mean the line destroyModalWindow(); is being called too early? Once the loop has processed there might be some clinet / server delay?? Another thing I noticed was the timed trigger event, even though its set to a 1 second delay, takes about 6 seconds on a round trip from the client to Web Application Server!!!! So even though on the WAS its processing it every second, it takes almost 6-7 seconds for it to render on the client browser!
    Has anyone else noticed this delay in rendering to code execution? Is it possible the Web Dynpro may terminate earlier than expected or sometimes we might not even see the results because time taken to render is slower than time taken to process request?
    What are peoples' thoughts?
    MM

    Sorry if I misinterpret your question...
    Remember Web Dynpro is server side technology. So no actual rendering happens at all until all code has been executed, then wdDoModify is called, and then output is generated and sent to the browser for rendering. Of course I can't see your code in it's completion, but the modal window should never display under any circumstances, as the call to create() and then destroy() happen within the same execution cycle, from what I can tell of your snippet.

  • TIme taken to execute query

    Hi,
    HOW TO FIND OUT TIME TAKEN TO EXECUTE SELECT QUERY IN SAP, SAY FOR EXAMPLE
    SELECT * FROM MARA WHERE MATNR BETWEEN '100' AND '1000'.
    HOW TO PRINT TIME TAKEN TO EXECUTE ABOVE QUERY i.e. TIME IN MICROSECONDS...
    IF YOU HAVE SAMPLE PROGRAM THEN PLEASE LET ME KNOW.
    THANKS,
    JOHN.

    just declare.
    END-OF-SELECTION.
      GET TIME.
      end_dt = sy-datum.
      end_tm = sy-uzeit.
    <b>ex--</b>
    select * from ekko into table ekko.
    get time.
    t1 = sy-uzeit.
    select * from ekko into table ekko.
    get time.
    t2 = sy-uzeit.
    write :/ t1.
    write :/ t2.
    diff = t2 - t1.
    write :/ 'Time Taken : ' , diff.

  • Waiting the main thread till all child thread has completed

    I am in the process of developing a batch application in Java 5.0 which extensively uses the java.util.concurrency API. Here is a small description of what the batch process will do,
    1. Retrieve values from DB and populate a blocking queue in main thread.
    2. Instantiate a Threadpool by calling, Executors.newFixedThreadPool(2)
    3. Invoking the following block of code from the main thread,
    while(!iBlockingQueue.isEmpty()) {
        AbstractProcessor lProcessor = new  DefaultProcessor((BusinessObject)iBlockingQueue.remove());
        iThreadPool.execute(lProcessor);
    }DefaultProcessor is a class that extends Thread.
    4. Invoking the following block of code from the main thread,
    iThreadPool.shutdown();
    try {
         iThreadPool.awaitTermination(30, TimeUnit.SECONDS);
         } catch (InterruptedException interruptedException) {
              iLogger.debug("Error in await termination...", interruptedException);
    Since, this is the first time I am using the java.util.concurrency API, I want to know whether this is the right way to wait for all the child threads to complete before executing further statements in the main (parent) thread. Or do I necessariliy have to call join() to ensure that the main thread waits for all the child threads to finish which can only happen when the queue is empty.
    Please note here that as per the requirements of the application the blocking queue is filled only once at the very beginning.
    I will appreciate any inputs on this.
    Thanks.

    looks like you would be waiting on a queue twice, once in the loop and again, under the hood, in the threadpool's execute()
    the threadpool's internal queue is all that is needed
    if your iBlockingQueue is also the threadpool's internal queue, you might have a problem when you remove() the BusinessObject
    by making DefaultProcessor extend Thread you are, in effect, implementing your own threadpool without the pooling
    DefaultProcessor need only implement Runnable, it will be wrapped in a thread within the pool and start() called
    to implement a clean shutdown, I suggest writing DefaultProcessor.run() as an infinite loop around the blocking queue poll(timeout) and a stop flag that is checked before going back to poll
    class DefaultProcessor implements Runnable {
      private BlockingQueue myQ;
      private boolean myStopFlag;
      DefaultProcessor( BlockingQueue bq ) { myQ = bq; }
      public void run() {
        BusinessObject bo = null;
        while( !myStopFlag && (bo=myQ.poll( 10, SECONDS )) ) {
          // business code here
      public void stop() { myStopFlag = true; }
    } Now, after iThreadPool.shutdown(), either call stop() on all DefaultProcessors (or alternatively send "poison" messages to the queue), and give yourself enough time to allow processing to finish.

  • Running bat file in Child Thread

    Hi
    Please first of all i will tell you my application flow.
    I have an application you can say Parent Process/application , In execution of this Process or thread my application start/run batch file before dying using "exec() funtion" .In batch i have some scripts.and after initiating batch command my application main process ends up.
    Now problem is
    I am not sure that child process or Batch script which main program called is alive when my main application closed or its running?
    i want to see its output on console?
    Is it possible that Parent Thread ends up and child is still running , how can i achieve this .
    OR is it possible that i create seprate thread to start batch and my main thread ends. and i will show batch file output on console.

    I'm having a hard time understanding what you're
    saying, so here are a few general things that may be
    relevant:Sorry for that , well you are very much near which i want.But Thanks
    * Child threads can keep running after the thread
    that spawned them dies. You don't need to do anything
    special here.
    * The VM will exit when there are no more non-daemon
    threads running. So if you make all threads other
    than your main thread daemons, then when main ends,
    the rest of the threads will die and the VM will
    exit. See Thread.setDaemon.Here in above two point i have confusion.that by VM you mean Parent process,
    VM is parent process of all java programs that we run.please clarify this
    Lets say VM is parent process than your first statement is no valid as in first you say that parent die it will not effect child threads.
    well i have test this case with my program i write a program like
    public class ThreadTest
         public static void main(String [] arg)
              Work work=new Work(1000);
              System.out.println("Main Thread Started"+work.isDaemon());
              work.setDaemon(false);
              work.start();
              System.out.println("Main Thread stopped");
    class Work extends Thread
         int count=0;
         public Work(int cou)
              super("Workere");
              count=cou;
         public void run()
              while(count-->0)
                   System.err.println("Worker Thread is running................");
    }Now bydefault work thread is deamon,when all work thread steps executed program finished, tell me here as its concurent execution,
    main is alive or die when it execute its all statements or it waits for work thread which it spawned.
    Secondly when i change deamon to true, when main statements finished it also stoped work thread.mean work thread just print some messages.
    Actually what i want is that, when my main progam ends up, before ending it spawned new thread which start batch script and i want to see its output on seprate screen just like when we run IE with exec it starts IE window.
    Hope fully this time its clear

  • How to show the processing time taken for a BPEL process in BAM report.

    Hi All,
    I have the data as below in the Data object. I would like to show the time taken for each order to complete in the report.
    instance Id     order Id     product Name     product Code     price     status     instance Time      updaterName
    1360010     ord004     Guitar     prod003     2000     requested     9/22/2008 12:12:11 PM     Invoke_InsertSalesOrder
    1360010     ord004     Guitar     prod003     2000     Approved     9/22/2008 12:15:11 PM     Invoke_OrderStatusUpdate
    This data comes from simple BPEL process where sensors are configured at the start and end of BPEL process. Also have a human task activity in between to create the time difference.
    In Enterprise link design studio, I tried to calculate the time difference using expression calculator and store it as calculated field. But that doesn't seems to work because when I execute the plan, second sensor data reaches only after human approval whereas first sensor data would be waiting for calculation and ultimately nothing comes into data object.
    How and where the calculation be done to show the processing time in the report. Please someone throw some light on this.
    Regards
    Jude.
    Edited by: user600726 on Sep 30, 2008 1:30 AM

    I would suggest modifying your data object so that the data can all be in a single row and use the sensor at the end of the process to upsert (update) the row created by the sensor at the start of the process. The time difference between two fields in the same row is then an easy calculation on a BAM report -- No EL plan should be needed.

  • Why can't I interrupt the main thread from a child thread with this code?

    I am trying to find an elegant way for a child thread (spawned from a main thread) to stop what its doing and tell the main thread something went wrong. I thought that if I invoke mainThread.interrupt() from the child thread by giving the child thread a reference to the main thread, that would do the trick. But it doesn't work all the time. I want to know why. Here's my code below:
    The main class:
    * IF YOU RUN THIS OFTEN ENOUGH, YOU'LL NOTICE THE "Child Please!" MESSAGE NOT SHOW AT SOME POINT. WHY?
    public class InterruptingParentFromChildThread
         public static void main( String args[] )
              Thread child = new Thread( new ChildThread( Thread.currentThread() ) );
              child.start();
              try
                   child.join();
              catch( InterruptedException e )
    // THE LINE BELOW DOESN'T GET PRINTED EVERY SINGLE TIME ALTHOUGH IT WORKS MOST TIMES, WHY?
                   System.out.println( "Child please!" );
              System.out.println( "ALL DONE!" );
    The class for the child thread:
    public class ChildThread implements Runnable
         Thread mParent;
         public ChildThread( Thread inParent )
              mParent = inParent;
         public void run()
              System.out.println( "In child thread." );
              System.out.println( "Let's interrupt the parent thread now." );
              // THE COMMENTED OUT LINE BELOW, IF UNCOMMENTED, DOESN'T INVOKE InterruptedException THAT CAN BE CAUGHT IN THE MAIN CLASS' CATCH BLOCK, WHY?
              //Thread.currentThread().interrupt();
              // THIS LINE BELOW ONLY WORKS SOMETIMES, WHY?
              mParent.interrupt();
    }

    EJP wrote:
    I'm not convinced about that. The wording in join() suggests that, but the wording in interrupt() definitely does not.Thread.join() doesn't really provide much in the way of details, but Object.wait() does:
    "throws InterruptedException - if any thread interrupted the current thread +before+ or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."
    every jdk method i've used which throws InterruptedException will always throw if entered while a thread is currently interrupted. admitted, i rarely use Thread.join(), so it's possible that method could be different. however, that makes the thread interruption far less useful if it's required to hit the thread while it's already paused.
    a simple test with Thread.sleep() confirms my expected behavior (sleep will throw):
    Thread.currentThread().interrupt();
    Thread.sleep(1000L);

  • Query Execution time - Elapsed time v Actual time taken

    Hi All,
    I have this scenario where I am querying a single table with the following results. It is a very heavy query in that there are multiple aggregate functions and multiple unions on it. Even if the query is written poorly (i doubt it is) why would the actual
    time taken to execute the query be much more than the statistics provided through the following commands?
    SET STATISTICS IO ON;
    SET STATISTICS TIME ON;
    Attached are the stats provided for the relevant query in question.
    Table '123456789_TEMP_DATA'. Scan count 178, logical reads 582048, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    SQL Server Execution Times:
       CPU time = 936 ms,  elapsed time = 967 ms.
    2014-01-06 17:36:41.383
    Now, although the CPU Time/Elapsed time shows that it takes less than a second, it actually takes more than 15 seconds to fetch the results. (This is the actual time that you get on the bottom bar of the Query pane as well.)
    What is the reason? Why is it that there is such a big discrepancy between the numbers? How can I improve this situation?
    Thanks!

    Yes. I am returning a huge number of rows to the client. 
    The query is simply against a single table. 
    Select
     'First Record',AVG(COLUMN1),STDEV(COLUMN1
    ),COUNT(COLUMN1)
    FROM [TABLE1] WHERE (SOME CONDITION)
    UNION ALL
    Select  'Second Record',AVG(COLUMN2),STDEV(COLUMN2),COUNT(COLUMN2) FROM [TABLE1]
    WHERE (SOME OTHER CONDITION)
    Imagine there are 178 records fetched in this manner with 178 UNIONs. The WHERE clause will always change for each SELECT statement.
    Now, the question is not so much about the query itself, but why the execution time is actually 15 seconds whilst the SQL STATISTICS show it to be 936ms (<1 second)
    Thanks!

  • Time-taken in access.log

    hi,
    I would like to know if the time-taken parameter in the extended format log represent
    the total time of the request (including the sleep time when all the threads are
    occupied) or not.
    thanks
    Alain

    "joerg" <[email protected]> wrote:
    >
    Does the time-taken in access.log include network latency to web-client
    For example given a request for xyz.jsp. What is included in the transaction-time
    We are using WLS6.1 SP3.I think the access log will only record how long the weblogic servers took to
    process a request.

  • Time taken in each section of Mapping

    Hi All,
    One of my mappings is taking a very long to execute in production db. Is there anyway/ any table which lets me view the times taken for each step in the mapping?
    I tried to use Debug mode by opening the mapping in OWB but the debug mode is a lot slower than the mapping itself when deployed - hence i am not able to know accurately where the actual problem might be.
    thanks.

    Hi
    The OWB browser has runtime reports that will let you see the steps and timings.
    There are a bunch of reports in the blog here on the runtime audit tables that you can use in SQLDeveloper, or just rip off the SQL;
    http://blogs.oracle.com/warehousebuilder/2010/10/owb_sql_reports_in_code_samples.html
    Download the zip, either use SQLDev with the reports or take the file OWBReports.xml and look at the SQL in it and use wherever.
    Cheers
    David

Maybe you are looking for

  • Trouble capturing waveform from PXI-4472

    I'm really a very green newbie at this stuff, so bear with me... I've got a PXI-4472 data acquisition board and a PXI-5411 waveform generator. I've connected the arbitrary out of the 5411 to the channel 0 in on the 4472. An external oscilloscope show

  • Rebel T4i Kit with 18-135mm Lens, STM lens like Amazon?

    Amazon has it for the same price, but I noticed it is listed as the STM lens, which is a new lens specifically built for the t4I. Bestbuy has it listed for the same price, but doesn't list it with STM. No point in buying the same camera with an older

  • Anyone used PL/FLOW with APEX in Oracle 11g?

    Greetings. I'm trying to find out if any of you have successfully used SourceForge's PL/FLOW with APEX in an 11g environment. References to PL/FLOW seem to be limited to 9i and I need to have some assurance that it would be compatible in a more updat

  • Changing IP address in Solaris 10 different from Sol 9?

    I recently needed to change the IP address of 2 new Solaris 10 Sparc boxes. I made the normal changes /etc/hosts /etc/hostname.bge0 /etc/resolv.conf /etc/netmasks /etc/nodename & /etc/defaultrouter (why can't we get these into one file?) But when reb

  • Can't Download Flash Pro CC

    When I try to download Flash Pro CC, it says, "Flash Professional is a desktop app so you'll want to download it from your computer." Thing is, I'm on my computer.