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;
    }
0

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I updated the original post to show the solution.
Since the PID won't change, I would place it in a constant so it is only calculated once.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.