Results 1 to 17 of 17
  1. #1
    petec is offline Member
    Join Date
    Feb 2014
    Location
    Near Buffalo NY
    Posts
    33
    Rep Power
    0

    Default How Can I Detect When My Program Is Ending

    I have java program that I am debugging with NetBeans. In it I open a serial com port. It seems that if I exit the program the serial port is not closed so I cannot get the port the next time I start the program.

    Is there a way I can detect that either the user clicked the "X" in the upper ight of the GUI or I clicked the "Stop Button" in NetBeans?

    Thanks In Advance,

    Pete

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,013
    Rep Power
    10

    Default Re: How Can I Detect When My Program Is Ending

    You can use a shutdown hook to detect when the JVM exits, or you can add a WindowListener to your JFrame to detect when that closes.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    petec is offline Member
    Join Date
    Feb 2014
    Location
    Near Buffalo NY
    Posts
    33
    Rep Power
    0

    Default Re: How Can I Detect When My Program Is Ending

    Thanks.

    I'm googling it now.

    So far two "solutions" are giving me problems.

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,013
    Rep Power
    10

    Default Re: How Can I Detect When My Program Is Ending

    If you're having trouble, I suggest posting an SSCCE showing exactly what you've tried and where you're stuck.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    petec is offline Member
    Join Date
    Feb 2014
    Location
    Near Buffalo NY
    Posts
    33
    Rep Power
    0

    Default Re: How Can I Detect When My Program Is Ending

    I have been doing more experimenting. If I halt the program when debugging in NetBeans the shutdownhook is not utilized.

    I will have to come uo with another way to terminate the program or close the comports.

    Thanks
    Pete

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,728
    Blog Entries
    7
    Rep Power
    21

    Default Re: How Can I Detect When My Program Is Ending

    Quote Originally Posted by petec View Post
    I have been doing more experimenting. If I halt the program when debugging in NetBeans the shutdownhook is not utilized.

    I will have to come uo with another way to terminate the program or close the comports.
    Didn't the shutdown hook work for you? Read the details in the API documentation of the Runtime class.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  7. #7
    petec is offline Member
    Join Date
    Feb 2014
    Location
    Near Buffalo NY
    Posts
    33
    Rep Power
    0

    Default Re: How Can I Detect When My Program Is Ending

    Jos,

    I think the problem is, when I terminate the NetBeans debug session using a forced stop (a status bar across the bottom has an "x" at the end of it and I click that) it doesn't go through the shutdownhook. But I believe the comports are still open and left that way because when I run again the port I opened during the last session is no longer available.

    I have to go to windows, device manager, delete the comport and reinstall it so that it is found the next time I start a debug.

    I am starting to believe I will not be able to use java for this project because of the serial comport problems I keep hitting. I say this after almost three weeks of "learning" java.

    Thanks,

    Pete

  8. #8
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,013
    Rep Power
    10

    Default Re: How Can I Detect When My Program Is Ending

    It turns out that shutdown hooks aren't triggered when you hit the "stop" button of an IDE like eclipse or netbeans, at least on Windows. Do a quick google search of "java eclipse stop doesn't trigger shutdown hook" or check out these:
    java - How to get shutdown hook to execute on a process launched from Eclipse - Stack Overflow
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=38016
    java - ShutdownHook in eclipse - Stack Overflow

    Keep in mind that similar problems exist when you kill the program from the Windows task manager as well.

    I don't know whether other languages have workarounds for this, but I wouldn't be surprised if you ran into similar issues no matter which language you chose.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. #9
    petec is offline Member
    Join Date
    Feb 2014
    Location
    Near Buffalo NY
    Posts
    33
    Rep Power
    0

    Default Re: How Can I Detect When My Program Is Ending

    I sort of suspected the hooks wouldn't work when hitting the stop button. And, most likely it would be the same for any development platform in any language.

    My real problem is getting reliable results for comports using java. Often java can't find the comports but windows shows them and I can open up a terminal session with hyperterminal or other terminal programs and the comport is there and I can use it. Googling for java and comport. RXTX, javacomm, gets millions of hits and I have spent hours studying them, trying them..unsuccessfully... modifying them...etc.

    I need to find the right forum where others are having the same problems and we solve this together.

    Thanks

    Pete

  10. #10
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    4,013
    Rep Power
    10

    Default Re: How Can I Detect When My Program Is Ending

    Quote Originally Posted by petec View Post
    I need to find the right forum where others are having the same problems and we solve this together.
    That would be my advice. Post in the forums of the libraries you mentioned, you'll get more specific help there. Good luck!
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  11. #11
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,260
    Rep Power
    6

    Default Re: How Can I Detect When My Program Is Ending

    I'm pretty sure JosAH has some things to say on this subject if I have to believe his recent little pet projects, but you have to apply a trick to get his attention.

    BEER! GROLSCH!

    There, now it's only a waiting game.

    What code are you using to enumerate the comm-ports? RxTx 'should' work just fine in that respect.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #12
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: How Can I Detect When My Program Is Ending

    I am starting to believe I will not be able to use java for this project because of the serial comport problems I keep hitting.
    A quick fundamental question... is the com port released properly if you start up your application normally (outside NetBeans) before closing it? If it does, then there's no reason to abandon Java just because you're having difficulties working with it in NetBeans. There are other ways to debug Java applications, e.g., by remotely attaching a debugger to it, inserting println/logging statements, adding unit tests, etc. You just need to change your development workflow slightly to accommodate.

    So it seems that both NetBeans and Eclipse have problems with not executing the shutdown hook for applications started via the IDE if you press the IDE's stop/terminate button. In a way this is understandable because the shutdown hook is to be executed when the JVM exits, but you wouldn't want your IDE to exit when you press the stop/terminate button.

    Why not try a different approach - by listening for the application's window events? Below is a quick example I modified from Oracle's HelloWorldSwing sample application:

    Java Code:
    import java.awt.Dimension;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.awt.event.WindowStateListener;
    
    import javax.swing.*;
    
    public class HelloWorldSwing {
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
         */
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("HelloWorldSwing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            //Add the ubiquitous "Hello World" label.
            JLabel label = new JLabel("Hello World");
            frame.getContentPane().add(label);
            frame.setPreferredSize(new Dimension(320, 240));
    
            //Display the window.
            frame.pack();
            frame.setVisible(true);
    
    //        frame.addWindowStateListener(new MyWindowAdapter());
            frame.addWindowListener(new MyWindowListener());
        }
    
        private static final class MyWindowListener implements WindowListener, WindowStateListener {
    
        	private void printEvent(WindowEvent e) {
    			System.out.println("old state: " + e.getOldState());
    			System.out.println("new state: " + e.getNewState());
    			System.out.println("param string: " + e.paramString());
        	}
    
    		@Override
    		public void windowOpened(WindowEvent e) {
    			System.out.println("windowOpened");
    			printEvent(e);
    		}
    
    		@Override
    		public void windowClosing(WindowEvent e) {
    			System.out.println("windowClosing");
    			printEvent(e);
    		}
    
    		@Override
    		public void windowClosed(WindowEvent e) {
    			System.out.println("windowClosed");
    			printEvent(e);
    		}
    
    		@Override
    		public void windowIconified(WindowEvent e) {
    			System.out.println("windowIconified");
    			printEvent(e);
    		}
    
    		@Override
    		public void windowDeiconified(WindowEvent e) {
    			System.out.println("windowDeiconified");
    			printEvent(e);
    		}
    
    		@Override
    		public void windowActivated(WindowEvent e) {
    			System.out.println("windowActivated");
    			printEvent(e);
    		}
    
    		@Override
    		public void windowDeactivated(WindowEvent e) {
    			System.out.println("windowDeactivated");
    			printEvent(e);
    		}
    
    		@Override
    		public void windowStateChanged(WindowEvent e) {
    			System.out.println("windowStateChanged");
    			printEvent(e);
    		}
        }
    
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
    			@Override
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    The idea is you can attach a WindowListener to your application's JFrame, and add the com port-closing code into the appropriate method in the listener. You can try out the above example in NetBeans, and you should find that windowClosing is called when the example is started from both an IDE and command line. This is where you can put your com port-closing code.

    Hth!

  13. #13
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,260
    Rep Power
    6

    Default Re: How Can I Detect When My Program Is Ending

    Quote Originally Posted by jashburn View Post
    In a way this is understandable because the shutdown hook is to be executed when the JVM exits, but you wouldn't want your IDE to exit when you press the stop/terminate button.
    Eclipse forks a different process for the java application you execute, it would be very poor design to run applications in the local JVM or that application will influence the stability of the IDE and the IDE will influence the stability of the program. I'm pretty sure any IDE does that.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  14. #14
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: How Can I Detect When My Program Is Ending

    That's a good point, gimbal2. Anyhow, reading from the bug reports for both NetBeans and Eclipse, it would seem it's not a trivial matter to fix the shutdown hook problem...

  15. #15
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,260
    Rep Power
    6

    Default Re: How Can I Detect When My Program Is Ending

    Indeed it isn't. But that's a lesson that we continuously have to learn and re-learn in our profession; things that are functionally easy tend to still be technically hard.

    Bit of history: I think in Netbeans versions before 4.0 the application actually was run in the local JVM, because I remember doing a System.exit() was a big problem.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,728
    Blog Entries
    7
    Rep Power
    21

    Default Re: How Can I Detect When My Program Is Ending

    Eclipse indeed fires up another JVM if it has to run your Java program; I think the OP shoots his own program in the neck, effectively aborting that other JVM so that it can't run its shutdown hook(s).

    kind regards,

    Jos

    ps. now where's my beer?
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,260
    Rep Power
    6

    Default Re: How Can I Detect When My Program Is Ending

    That's another thread and you still have to answer to it.

    EDIT: wait, what? No it is THIS thread. Holy crud you'd think I've been sampling the bottle myself. If you'll excuse me, I'm going to have some choice words with myself -------------> over there.
    Last edited by gimbal2; 02-28-2014 at 05:01 PM.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. How to have program detect own name
    By DarkHarbinger in forum Advanced Java
    Replies: 4
    Last Post: 08-14-2012, 09:20 AM
  2. Ending Program With While Loop
    By method22 in forum New To Java
    Replies: 3
    Last Post: 11-28-2011, 07:40 PM
  3. ending a csv
    By paul1024 in forum New To Java
    Replies: 2
    Last Post: 05-04-2011, 03:14 AM
  4. Why is my java applet program not ending?
    By Ryamza in forum New To Java
    Replies: 3
    Last Post: 05-04-2011, 02:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •