Java Concurrency - Process (Main thread)

About

process in Java

A process in Java is:

  • started by a main class.
  • implemented as a main thread that can create other thread.

It has:

  • a self-contained execution environment.
  • a complete, private set of basic run-time resources; in particular, each process has its own memory space.

Management

Creation

Most implementations of the Java virtual machine run as a single process. A Java application can create additional processes using a ProcessBuilder object.

List

The jps command will report the local VM identifier, or lvmid for each instrumented JVM found on the target system (The lvmid is generally the operating system's process identifier).

More Java - jps (Java Process Utility)

Get Pid

From Jps

with Java - jps (Java Process Utility)

jps | grep -i name | awk '{print $1}'

From Java

import sun.management.VMManagement;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public static int getCurrentPID() {
    try{
        java.lang.management.RuntimeMXBean runtime = 
            java.lang.management.ManagementFactory.getRuntimeMXBean();
        java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
        jvm.setAccessible(true);
        sun.management.VMManagement mgmt = 
           (sun.management.VMManagement) jvm.get(runtime);
        java.lang.reflect.Method pid_method = 
            mgmt.getClass().getDeclaredMethod("getProcessId");
        pid_method.setAccessible(true);
        return (Integer) pid_method.invoke(mgmt);
    }
    catch(Exception e){
        e.printStackTrace();
        System.out.println("Failed at getting the process ID");
        System.exit(0);
    }
}

https://stackoverflow.com/questions/11685408/java-get-pid-of-external-process-by-command-line-in-windows-7

Name

https://github.com/airlift/procname - Set process name for Java on Linux


Powered by ComboStrap