Java : ProcessHandle.Info with Examples
ProcessHandle.Info (Java SE 19 & JDK 19) API Examples.
You will find code examples on most ProcessHandle.Info methods.
Summary
Please see also : Process, ProcessHandle
public class Main {
public static void main(String[] args) {
final var handle = ProcessHandle.current();
final var info = handle.info();
System.out.println("user = " + info.user());
System.out.println("total cpu time = " + info.totalCpuDuration());
}
}
// Result
// ↓
//> java Main
//user = Optional[MY-PC\xxxx]
//total cpu time = Optional[PT0.09375S]
Methods
Optional<String[]> arguments ()
The following code runs on Linux.
public class Main {
public static void main(String[] args) {
System.out.println("args : " + Arrays.toString(args));
final var handle = ProcessHandle.current();
final var info = handle.info();
info.command().ifPresent(command -> {
System.out.println("command = " + command);
});
info.commandLine().ifPresent(commandLine -> {
System.out.println("commandLine = " + commandLine);
});
info.arguments().ifPresent(arguments -> {
System.out.println("arguments = " + Arrays.toString(arguments));
});
}
}
// Result
// ↓
//$ java Main aaa bbb
//args : [aaa, bbb]
//command = /home/xxxx/openjdk/jdk-19.0.2/bin/java
//commandLine = /home/xxxx/openjdk/jdk-19.0.2/bin/java Main aaa bbb
//arguments = [Main, aaa, bbb]
Optional<String> command ()
Please see arguments().
Optional<String> commandLine ()
Please see arguments().
Optional<Instant> startInstant ()
public class Main {
public static void main(String[] args) {
System.out.println("current time : " + Instant.now());
// Uses about 15 seconds of CPU time.
final var start = System.nanoTime();
while (true) {
if (System.nanoTime() - start >= 1000000000L * 15) {
break;
}
}
final var handle = ProcessHandle.current();
final var info = handle.info();
info.startInstant().ifPresent(instant -> {
System.out.println("start instant = " + instant);
});
info.totalCpuDuration().ifPresent(duration -> {
System.out.println("total cpu time = " + duration);
});
}
}
// Result
// ↓
//> java Main
//current time : 2023-03-25T07:52:44.806974500Z
//start instant = 2023-03-25T07:52:44.727Z
//total cpu time = PT14.828125S
Optional<Duration> totalCpuDuration ()
Please see startInstant().
Optional<String> user ()
public class Main {
public static void main(String[] args) {
final var handle = ProcessHandle.current();
final var info = handle.info();
info.user().ifPresent(user -> {
System.out.println("user = " + user);
});
}
}
// Result
// ↓
//> java Main
//user = MY-PC\xxxx
Related posts
- API Examples