1 Reply Latest reply: Sep 11, 2009 7:32 AM by 577913 RSS

    How do I trap Control-break signal in Java

    843829
      I have my own utitlity class as follows to generate a heap dump using JMX. I wanted to hook this class when a user press Ctrl-break on the console of running process. Is there a way to trap the control break signal before sent to JVM and call this method?

           private void dumpHeap(){
                try {
                     String url = "service:jmx:rmi:///jndi/rmi://localhost:9004/jmxrmi";
                     JMXServiceURL jmxURL = new JMXServiceURL(url);
                     JMXConnector connector = JMXConnectorFactory.connect(jmxURL);
                     MBeanServerConnection connection = connector
                               .getMBeanServerConnection();

                     String hotSpotDiagName = "com.sun.management:type=HotSpotDiagnostic";
                     ObjectName name = new ObjectName(hotSpotDiagName);
                     String operationName = "dumpHeap";

                File tempFile = null;
                     File dir = new File("C://folder");
                     try {
                          tempFile = File.createTempFile("dump", ".hprof", dir);
                     } catch (IOException ioe) {
                          System.out
                                    .println("Exception creating temporary file : " + ioe);
                     }

      tempFile.delete();
                     String dumpFilename = tempFile.getAbsolutePath();
                     System.out.println(dumpFilename);
                     Object[] params = new Object[] { dumpFilename, Boolean.TRUE };
                     String[] signature = new String[] { String.class.getName(),
                               boolean.class.getName() };
                     Object result = connection.invoke(name, operationName, params,
                               signature);
                     System.out.println("Dumped to " + dumpFilename);

                } catch (Exception e) {
                     e.printStackTrace();
                }

           }
        • 1. Re: How do I trap Control-break signal in Java
          577913
          Use [Runtime#addShutdownHook|http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29] - please read description carefully..

          Look at depracted [Runtime#runFinalizersOnExit|http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#runFinalizersOnExit%28boolean%29]

          Kind regards,
          /-/