0

These methods rely on the below imports. These are old and from reading shouldn't be using it. This only works with java 6 anyway and I would like to get this updated to java 8.

Does anyone know how to get the PID in Java 8 on OS X ?

import sun.jvmstat.monitor.*;
import java.lang.management.*;


        public String getUsageDescription()
        {
            System.out.println("** Get Usage Description");
            int pid = 0;
            RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
            pid = Integer.parseInt(rt.getName().substring(0,rt.getName().indexOf("@")));
            System.out.println("Run Time PID = "+pid);
            return new String(getDeviceName()+" "+Integer.toString(pid));
        }


        public static boolean isPIDInUse(int pid)
        {
            try{
                String s = null;
                int java_pid;
                MonitoredHost host = MonitoredHost.getMonitoredHost(s);
                for(Object activeVmPID : host.activeVms())
                {
                    java_pid = (Integer)activeVmPID;
                    System.out.println("****************PID = "+java_pid);
                    if(java_pid == pid){
                        System.out.println("In Use\n");
                        return true;
                    }
                }
            }
            catch(Exception e)
            {
                System.out.println("Exception:  "+e.getMessage());
            }
            return false;

        }

Solution:

public static boolean isPIDInUse(int pid) {

        try {

            String s = null;
            int java_pid;

            RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
            java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf("@")));

            if (java_pid == pid) {
                System.out.println("In Use\n");
                return true;
            }
        } catch (Exception e) {
            System.out.println("Exception:  " + e.getMessage());
        }
        return false;
    }
PartialData
  • 55
  • 1
  • 10

1 Answers1

1

Use the first method. It works in Java 8 and doesn't use internal APIs.

Note you don't need to use new String(String)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130