View Javadoc
1   package org.kuali.common.jute.runtime;
2   
3   import static com.google.common.base.Optional.absent;
4   import static com.google.common.collect.Iterables.getFirst;
5   import static java.lang.Integer.parseInt;
6   import static org.apache.commons.lang3.StringUtils.trimToNull;
7   
8   import java.lang.management.ManagementFactory;
9   
10  import javax.inject.Provider;
11  
12  import com.google.common.base.Optional;
13  import com.google.common.base.Splitter;
14  
15  public enum ProcessIdProvider implements Provider<Optional<Integer>> {
16      INSTANCE;
17  
18      @Override
19      public Optional<Integer> get() {
20          try {
21              // From the Javadoc -> "The returned name string can be any arbitrary string"
22              // In practice, the name is *usually* the pid followed by the @ character, but there are no guarantees
23              String name = ManagementFactory.getRuntimeMXBean().getName();
24              Iterable<String> tokens = Splitter.on('@').split(name);
25              String first = getFirst(tokens, null);
26              String trimmed = trimToNull(first);
27              if (trimmed == null) {
28                  return absent();
29              } else {
30                  int pid = parseInt(trimmed);
31                  return Optional.of(pid);
32              }
33          } catch (Throwable e) {
34              // If anything goes wrong at any point, just return absent()
35              return absent();
36          }
37      }
38  
39  }