Should the main thread always call join or is it ok to let it finish?

Should the main thread always wait (e.g. join) for other, non-daemon, threads to finish before it exits itself, or is it ok to let it finish?
I've been programming in Java for quite some time now and I've never noticed programs doing anything odd after letting the main thread exit while other threads are still doing work. I've recently noticed however that a thread called "DestroyJavaVM" starts up as soon as "main" exits so I'm now wondering if I'm not working with "main" correctly.

I have read some books in java and almost all of them emphasize on main thread finishing last and they also warn that if main thread does not finish last then JVM might hang.
But in almost all my concurrency problems main thread is the first one to finish ha ha... and JVM has never hanged.
May be they suggest this because main thread finishing last is good programming practice.

Similar Messages

  • 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);

  • What exactly is the main thread?

    please consider this code:
    public class Foo {
        public static void main(String[] args) {
              ((Foo) Thread.currentThread()).bar(); // <--- error. see stack trace below.
        public void bar() {
            System.out.println("--bar()--");
    }stack trace: Exception in thread "main" java.lang.ClassCastException: java.lang.Thread cannot be cast to testingarea.Foo
    So what does this say about the main entry thread? is it an instance of "Foo"? or an instance of java.lang.Thread? If an instance of "Foo" why can't I invoke an instance method on the return value of "Thread.currentThread()"? If the main thread is an instance of java.lang.Thread, then where is the:
    "public void run();" method?
    While I can't think of any practical usage of this knowledge yet, but I'd still like to know. Thanks.
    Edited by: outekko on Mar 17, 2010 6:38 PM

    joshg_75 wrote:
    You should always refer to the javadoc for infomation of a method and its usage. In this case, refer to the javadoc of the Thread class.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html
    I suggest you also read up on usage of threads.Can you please share a little of your expertise in threads?
    Remember this is the "New To Java" forum, and I am just a beginner as you discovered. Any help from experts would be embraced. Before you became a thread expert, you must have started somewhere. I don't need immediate assistance, but whenever you get the time, why not cut/paste this into your IDE and take a look.
    public class Main {
      static ObjectOutputStream oos;
      static ObjectInputStream ois;
      public static void main(String[] args) {
        try {
          PipedInputStream pin = new PipedInputStream();
          PipedOutputStream pout = new PipedOutputStream(pin);
          oos = new ObjectOutputStream(pout);
          ois = new ObjectInputStream(pin);
          new OutThread().start();
          for(;;) {
            Thread t = (Thread) ois.readObject();
            t.start();
        } catch (Exception e) { e.printStackTrace(); }
          public static class OutThread extends Thread implements Serializable {
            public void run() {
              System.out.println("OutThread::run--> id# " + this.getId());
              try { Thread.sleep(1030); } catch (InterruptedException e) {  }
              try {
                oos.writeObject(this);
                hangAround();
              } catch (Exception e) { e.printStackTrace(); }
            public void hangAround() {
              for (;;) {
                System.out.println("_____waiting around... id# " + this.getId());
                try { Thread.sleep(5030); } catch (InterruptedException e) {  }
    }Not only do I appear to serialize instances of threads, the threads are actually running . So, does a live thread have private, non-transient, "state" that needs to be persisted? If so, why does serialization work? If not, why not write in the API that java.lang.Thread implements Serializable ? Whatever understanding (if any) I had of threads has melted to nothing. I am struggling with your field of expertise; please help me get back on track. Any assistance embraced.
    ps. don't offer friendly criticism by scolding my design of serialized threads. My only goal is to see if I can do it (and learn something along the way).

  • 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.

  • When opening a page, FF sometimes hangs for several minutes, the main thread consuming 100% of the running core

    I've not been able to detect a pattern of occurrence. It just happened now when I opened this page
    http://www.pcinpact.com/actu/news/66460-amd-catalyst-rage-vsync-opengl.htm
    soon after starting FireFox (which loaded the dozen tabs - in two windows - of my current session).
    Here is the stack of the main thread, as shown in Process Explorer :
    ntdll.dll!ZwQueryDirectoryFile+0xa
    wow64.dll!Wow64EmulateAtlThunk+0x8c77
    wow64.dll!Wow64SystemServiceEx+0xd7
    wow64cpu.dll!TurboDispatchJumpAddressEnd+0x2d
    wow64.dll!Wow64SystemServiceEx+0x1ce
    wow64.dll!Wow64LdrpInitialize+0x429
    ntdll.dll!RtlUniform+0x6e6
    ntdll.dll!RtlCreateTagHeap+0xa7
    ntdll.dll!LdrInitializeThunk+0xe
    ntdll.dll!NtQueryDirectoryFile+0x12
    xul.dll!??0Layer@layers@mozilla@@IAE@PAVLayerManager@12@PAX@Z+0x1589
    xul.dll!NS_NewLocalFile_P+0xb536
    xul.dll!?AccumulateMetricsForRun@gfxTextRun@@AAEXPAVgfxFont@@IIW4BoundingBoxType@2@PAVgfxContext@@PAVPropertyProvider@1@IIPAURunMetrics@2@@Z+0xdc07
    xul.dll!?AccumulateMetricsForRun@gfxTextRun@@AAEXPAVgfxFont@@IIW4BoundingBoxType@2@PAVgfxContext@@PAVPropertyProvider@1@IIPAURunMetrics@2@@Z+0xf951
    xul.dll!?Stroke@gfxContext@@QAEXXZ+0x2ad
    xul.dll!?Stroke@gfxContext@@QAEXXZ+0x9ab
    xul.dll!NS_InvokeByIndex_P+0x72f99
    xul.dll!?SanitizeMetrics@gfxFont@@IAEXPAUMetrics@1@H@Z+0x1048
    xul.dll!?Paint@gfxAlphaBoxBlur@@QAEXPAVgfxContext@@ABUgfxPoint@@@Z+0x2e2
    xul.dll!?ReleaseTextRun@gfxTextRunCache@@SAXPAVgfxTextRun@@@Z+0x4f6
    xul.dll!?TransformToNativeRect@gfxWindowsNativeDrawing@@QAEXABUgfxRect@@AAUtagRECT@@@Z+0x13c
    xul.dll!??0ImageContainerOGL@layers@mozilla@@QAE@PAVLayerManagerOGL@12@@Z+0x1318
    xul.dll!??0ImageContainerOGL@layers@mozilla@@QAE@PAVLayerManagerOGL@12@@Z+0x142c
    xul.dll!??0gfxSkipCharsIterator@@QAE@ABV0@@Z+0x85a
    xul.dll!??0ImageContainerOGL@layers@mozilla@@QAE@PAVLayerManagerOGL@12@@Z+0x1444
    xul.dll!??0gfxSkipCharsIterator@@QAE@ABV0@@Z+0x85a
    xul.dll!??0ImageContainerOGL@layers@mozilla@@QAE@PAVLayerManagerOGL@12@@Z+0x1444
    xul.dll!??0gfxSkipCharsIterator@@QAE@ABV0@@Z+0x85a
    the last two functions are called recursively over 40 times...

    Today, I was able to open the older version of the template if I only viewed the code first.  So I was able to narrow it down to one change I had made.  I had changed:
    <link href="/css/960grid.css" rel="stylesheet" type="text/css">
    to:
    <link href="http://mydomain.com/css/960grid.css" rel="stylesheet" type="text/css">
    When I tried to save the document, Dreamweaver hanged.  The document opened fine with all of the other changes I had made, although it couldn't find the CSS files (I had moved the site to another root locally).
    This really looks like a bug in Dreamweaver to me.  I've seen CSS links like this in other people's websites, so it does look like valid CSS to me.  Is there a workaround for this?

  • How to make the main() thread wait?

    I would like to know how to make the main() thread wait for another thread?If I use wait() method in main() method it says "non-static method wait() cannot be referenced from a static context",since main()
    is static.

    Here is an example how you may wait for a Thread in the main -
    but be careful, this is no real OO:
    public class WaitMain {
    // this is the thread class - you may also create
    // a runnable - I use a inner class to
    // keep my example simple
         public static class ThreadWait extends Thread{
              public void doSomething(){
                   synchronized(syncObject){
                        System.out.println("Do Something");
                        syncObject.notify();
              public void run(){
                   // sleep 10 seconds - this is
                   // a placeholder to do something in the thread
                   try{
                        sleep(10000);
                        doSomething();
                        sleep(10000);
                   catch(InterruptedException exc){
    // this is the object we wait for -
    // it is just a synchronizer, nothing else
         private static Object syncObject = new Object();
         public static void main(String[] args) {
              System.out.println("This will start a thread and wait for \"doSomething\"");
              ThreadWait t= new ThreadWait();
              t.start();
              synchronized(syncObject){
                   try{
    // this will wait for the notify
                        syncObject.wait();
                        System.out.println("The doSomething is now over!");
                   catch(InterruptedException exc){
              // do your stuff

  • How to blocks the main thread

    Hello,
    I have a multi-threaded application but the main thread doesnt blocks the application so the application quits just after started. Im using this code to block the main thread:
    /*BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
    for(;;) {
    try {
    r.readLine();
    catch (IOException e) {
    I tryed to just use for(;;){} but it causes 100% of CPU using. This code above its very dangerous because sometimes System.in blocks the entire application (all threads)
    Thanks a lot

    This application its a socket server, Im doing:
    main {
    Thread1 - createServer();
    Thread2 - createLogging();
    waitForServerShutDown();
    the createServer method must be placed in a thread, its must not blocks the application because createLogging(); must be executed just after the server was created and createLogging(); doesnt blocks the application then... I must block the main{} to keeps application running

  • HT201412 i have an iphone 4s and it just turned off and wouldnt turn back on until i got home and plugged it in to the mains. however it wont connect to my carrier and wont let me turn wifi on or use the internet. all my data is still in place, please HEL

    i have an iphone 4s and it just turned off and wouldnt turn back on until i got home and plugged it in to the mains. however it wont connect to my carrier and wont let me turn wifi on or use the internet. all my data is still in place. however when i disconnect from the charger it switches straight off immediately. it also just flashes up the apple icon (on 10 seconds, off 10 seconds.......) when i connect to either car charger or computer. it also resets itself every single time i turn it back on using the mains charger. please help me understand what is happening to my phone
    is there anything apple could do if i took it to one of their main shops???
    Kris (bulzy_23)

    Sounds like a hardware failure.
    Make an appointment at the genius bar and take it in for them to look at. It will probably need to be replaced.

  • How to hold the main thread, till response is received from the server?

    I have a program in which the GUI client(View program in Swings) sends a request to server (Manager program) , and waits for the response from Manager.
    The method used is waitForResponse() as follows
    <code>
    private void waitForResponse()
    m_blWaitFlag=true;
    //after response from manager m_blWait flag is set to false.
    while (m_blWaitFlag)
    try
    Thread.sleep(500);
    }catch(Exception r_ex)
    </code>
    And in notifyResponse() method, the wait flag is set to false
    as in,
    <code>
    public void notifyResponse(VcvResponse r_objResponse)
    m_blWaitFlag = false; //this line makes the thread to come out of the wait mode.
    </code>
    When I click a menu item, this request is sent and there is a wait for a response from manager.
    The problem is , this kind of waiting makes the system slow, and grey patches are seen immediately after clicking a menu item.
    Are there other ways of waiting??
    Thanks in advance

    When I click a menu item, this request is sent and there is a wait for a response from manager.This means you are using the GUI thread to send the request.
    The problem is , this kind of waiting makes the system slow, and grey patches are seen immediately after clicking a menu item.This means the GUI thread is waiting for the response. No GUI updates can occur while it is waiting.
    Are there other ways of waiting??Use another thread. e.g the main as you suggested. If you are using a callback, why do you have a thread waiting at all? WHy not do the things you would do when a response comes back in the call back?

  • How to start and stop a progress-bar thread before/after the main thread

    hi. I would appreciate any kind of help on my request.
    I have this as my main() function
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable(){
                   public void run(){                              
                        Options op = new Options();
                        OdessaClient oc = new OdessaClient(op);     
                        oc.setVisible(true);                    
         }Whenever I try to start a simple JFrame with an indeterminate progress bar on it just before the main function and stop it somewhere after I get a StackOverFlow error
    Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
         at java.awt.Component.show(Component.java:1302)
         at java.awt.Component.setVisible(Component.java:1253)
         at com.client.CylonBar.hide(CylonBar.java:25)
         at java.awt.Component.show(Component.java:1302)
         at java.awt.Component.setVisible(Component.java:1253)
    ...and so on...How must I implement something like it?

    Not precisely that way, but just off the top of my head, you would have to have a handle to the proccess (server) in the first window, then have a monitor program that allows you take this handle and end it. I would make this monitor program be the gateway to starting and stopping your server. To run a .bat file you can use runtime.exec().

  • Report does not show the main section while calling from forms 6i

    Hi
    I am running report from report from forms 6i but is does not show the data in main section, where as the data in the header section is ok.
    But when i run the same report independantly from report builder it show the both header and main section with relevent data.
    pl solve the matter
    thanks in advance

    can you tell me more about this, you might check if you are using different users when you call this report or if the user has all privileges to see all tables in this report

  • How to control the main thread?

    public static void main(String args[]) {
    Thread t = Thread.currentThread();
    System.out.println("Current thread: " + t);
    In the above code, i want to know more about currentThread() method...
    if i execute, i get an error message,can anyone help me in this regard?

    When i execute the program, the program has an output
    as below:
    current thread:[main,5,main]
    But a window opens telling that there is some error
    in the program...
    Why does it happen so?What is the EXACT text of the error message?

  • Blocking the applet and main threads ?

    The thread that runs the Applet callback methods like init() and start() is a thread named �applet-your.package.your.classname.class�.
    If I am doing a blocking method call, i.e. a method call that does not return immediately like doing I/O read on a socket connection, is it ok to do it on the thread mentioned above ? In other words, is it ok to hang/suspend/block the applet thread ?
    What about blocking the �main� thread that calls
    public static void main(String args[]) {�}
    Thanks.

    eminformatics, thanks for the reply.

  • Need blocking method without blocking main thread

    I have this problem:
    public void blockingMethod() {
      frame.setVisible(true);
      // wait for the user to click on a button on the frame
      return;
    }I want to make a method blocking until the user press a button on the frame. However, I can't make the current thread sleep or wait and then notify it when the button is pressed, because it is the main thread that calls this method. And the main thread is responsible for listening to events and repaint the frame.
    I could solve my problem by using a modal Dialog and let the user enter some data there and then exit the Dialog. Dialog.show() would block until the user exits it again. But I would rather use my frame, so I took a look at the code for Dialog.show() method, and it does something like this:
    EventDispatchThread dispatchThread =(EventDispatchThread)Thread.currentThread();
    * pump events, filter out input events for
    * component not belong to our modal dialog.
    * we already disabled other components in native code
    * but because the event is posted from a different
    * thread so it's possible that there are some events
    * for other component already posted in the queue
    * before we decide do modal show. 
    dispatchThread.pumpEventsForHierarchy(new Conditional() {
      public boolean evaluate() {
        return keepBlocking && windowClosingException == null;
    }, this);But EventDispatchThread is package protected, so I can't do this.
    Any suggestions? I think there are circumstances where you would like a method block, but where it is the main thread that calls the method (out of my control), and you would not like the main thread block unless you could make sure the gui would still repaint and events would run.

    Ah, nm. The main thread is not the same as the event thread.
    Whew! :)
    The first who reply will get the dukes.

  • Interrupting a main thread?

    At sometime in the executing of my main thread this start method is called:
    public void start() {
        final Runnable poller = new Runnable() { public void run() { poll(); } };
        final ScheduledFuture<?> pollHandle = scheduler.scheduleWithFixedDelay(poller, 5, 5, TimeUnit.SECONDS);
        final Thread shutdownHook = new Thread() { @Override public void run() { pollHandle.cancel(true); } };
        Runtime.getRuntime().addShutdownHook(shutdownHook);
      }Does this create a new thread or simply just tells the main thread to call the poll function in the specified time interval?
    If it creates a new thread does the thread calling start() just return after calling start leaving the new thread to call the poll() function?

    The scheduler will use an internal thread to time the polling action, so scheduleWithFixedDelay will return immediately.

Maybe you are looking for

  • X301 and Windows 7

    Hello, I installed Windows 7 on my X301 and have problems with three hardware devices. One is the fingerprint reader. It is shown in the device manager but I cannot find a vaild driver. The other two hardware devices I am not able to identify. Is the

  • No Compiling Error but doesn't work

    import java.awt.*; import java.awt.geom.*; import java.awt.event.*; import java.applet.*; public class javacw extends Applet implements KeyListener, Runnable      Area pandaArea;      Graphics2D g2d;      // Providing coordinate control for the Panda

  • Entity Framework - Execute Stored Procedures

    I want to execute stored procedure using entity framework. I am using entity framework 6. The stored procedure has SELECT and RETURN statement. How can I read the output from SELECT and RETURN statements using dbContext.Database.ExecuteSqlCommand or 

  • Scsi card for mdd

    i just inherited my wifes g4 mdd. she got the new g5 for christmas!!! can i take out the scsi card from my now old g4 400 mhz and shove it in an open slot on the mdd and have it work? or is there more to it than that? reason is i still have an old um

  • Sound out of sync when burning a movie on The Mac.

    I'm buring an AVI. movie just by right clicking and selecting burn the file to disc option and when I play the DVD on a seperate DVD player afte about 5 miniutes of film the sound is seconds out of sync from the actual movie, can anyone advise me? Th