Example usage for java.lang.management ManagementFactory getRuntimeMXBean

List of usage examples for java.lang.management ManagementFactory getRuntimeMXBean

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getRuntimeMXBean.

Prototype

public static RuntimeMXBean getRuntimeMXBean() 

Source Link

Document

Returns the managed bean for the runtime system of the Java virtual machine.

Usage

From source file:rems.Program.java

/**
 * @param args the command line arguments
 *///  ww  w  .  java 2s .c  om
public static void main(String[] args) {
    try {

        Global.UsrsOrg_ID = 3;
        Global.dataBasDir = "C:\\1_DESIGNS\\MYAPPS\\Enterprise_Management_System\\Enterprise_Management_System\\bin\\Debug\\Images\\test_database";
        Global.rnnrsBasDir = "C:\\1_DESIGNS\\MYAPPS\\Enterprise_Management_System\\Enterprise_Management_System\\bin\\Debug\\bin";

        String pname = ManagementFactory.getRuntimeMXBean().getName();
        if (pname.contains("@")) {
            Global.pid = Integer.parseInt(pname.substring(0, pname.lastIndexOf("@")));
        } else {
            Global.pid = Thread.currentThread().getId();
        }
        Global.HostOSNme = System.getProperty("os.name");
        System.out.println(Global.pid);
        System.out.println(Global.HostOSNme);

        String[] macDet = Global.getMachDetails();
        System.out.println(Arrays.toString(macDet));
        System.out.println(args.length);
        System.out.println(Arrays.toString(args));
        Global.errorLog += Global.pid + System.getProperty("line.separator") + Global.HostOSNme
                + System.getProperty("line.separator") + Arrays.toString(Global.getMachDetails())
                + System.getProperty("line.separator");
        //Global.writeToLog();
        if (args.length >= 8) {
            Global.rnnrsBasDir = StringUtils.strip(args[7], "\"");
            runnerName = StringUtils.strip(args[5], "\"");
            Global.errorLog = args[0] + System.getProperty("line.separator") + args[1]
                    + System.getProperty("line.separator") + args[2] + System.getProperty("line.separator")
                    + "********************" + System.getProperty("line.separator") + args[4]
                    + System.getProperty("line.separator") + args[5] + System.getProperty("line.separator")
                    + args[6] + System.getProperty("line.separator") + Global.rnnrsBasDir
                    + System.getProperty("line.separator");

            if (args.length >= 10) {
                Global.callngAppType = StringUtils.strip(args[8], "\"");
                Global.dataBasDir = StringUtils.strip(args[9], "\"");
                Global.errorLog += args[8] + System.getProperty("line.separator") + args[9]
                        + System.getProperty("line.separator");
                if (args.length == 11) {
                    Global.AppUrl = StringUtils.strip(args[10], "\"");
                    Global.errorLog += args[10] + System.getProperty("line.separator");
                }
            }
            Global.errorLog += "PID: " + Global.pid + " Running on: " + macDet[0] + " / " + macDet[1] + " / "
                    + macDet[2];
            Global.writeToLog();
            Global.runID = Long.valueOf(args[6]);
            do_connection(args[0], args[1], args[2], args[3], args[4]);
            Global.appStatPath = Global.rnnrsBasDir;
            //Program.updateRates("2015-07-02");
            if (Global.runID > 0) {
                Global.rnUser_ID = Long.valueOf(
                        Global.getGnrlRecNm("rpt.rpt_report_runs", "rpt_run_id", "run_by", Global.runID));
                Global.UsrsOrg_ID = Global.getUsrOrgID(Global.rnUser_ID);
            }

            if (!Global.globalSQLConn.isClosed()) {
                Global.globalSQLConn.close();
                boolean isLstnrRnng = false;
                if (Program.runnerName.equals("REQUESTS LISTENER PROGRAM")) {
                    int isIPAllwd = Global.getEnbldPssblValID(macDet[2],
                            Global.getEnbldLovID("Allowed IP Address for Request Listener"));
                    int isDBAllwd = Global.getEnbldPssblValID(Global.Dbase,
                            Global.getEnbldLovID("Allowed DB Name for Request Listener"));
                    if (isIPAllwd <= 0 || isDBAllwd <= 0) {
                        Program.killThreads();
                        Thread.currentThread().interrupt();
                        //Program.killThreads();
                        return;
                    }

                    isLstnrRnng = Global.isRunnrRnng(Program.runnerName);
                    if (isLstnrRnng == true) {
                        Program.killThreads();
                        Thread.currentThread().interrupt();
                        //Program.killThreads();
                        return;
                    }
                }
                Global.errorLog = "Successfully Connected to Database\r\n" + String.valueOf(isLstnrRnng)
                        + System.getProperty("line.separator");
                Global.writeToLog();
                String rnnPryty = Global.getGnrlRecNm("rpt.rpt_prcss_rnnrs", "rnnr_name", "crnt_rnng_priority",
                        Program.runnerName);

                if (isLstnrRnng == false && Program.runnerName.equals("REQUESTS LISTENER PROGRAM")) {
                    Global.updatePrcsRnnrCmd(Program.runnerName, "0", -1);
                    thread1 = new RqstLstnrUpdtrfunc("ThreadOne");
                    thread1.setDaemon(true);
                    thread1.setName("ThreadOne");
                    thread1.setPriority(Thread.MIN_PRIORITY);
                    //System.out.println("Starting ThreadOne thread...");
                    thread1.start();
                    Global.minimizeMemory();
                    if (Program.runnerName.equals("REQUESTS LISTENER PROGRAM")) {
                        //Thread for Generating Run Requests for Scheduled Programs/Reports
                        thread2 = new GnrtSchldRnsfunc("ThreadTwo");
                        thread2.setDaemon(true);
                        thread2.setName("ThreadTwo");
                        thread2.setPriority(Thread.MIN_PRIORITY);
                        //System.out.println("Starting ThreadTwo thread...");
                        thread2.start();

                        //Thread for Generating Run Requests for Scheduled Alerts
                        thread6 = new GnrtSchldAlertsfunc("ThreadSix");
                        thread6.setDaemon(true);
                        thread6.setName("ThreadSix");
                        thread6.setPriority(Thread.MIN_PRIORITY);
                        //System.out.println("Starting ThreadSix thread...");
                        thread6.start();

                        //Thread for Monitoring Scheduled Request Runs that are due but not running
                        // and starting their appropriate process runners
                        thread3 = new MntrSchdldRqtsNtRnngfunc("ThreadThree");
                        thread3.setDaemon(true);
                        thread3.setName("ThreadThree");
                        thread3.setPriority(Thread.MIN_PRIORITY);
                        //System.out.println("Starting ThreadThree thread...");
                        thread3.start();

                        //Thread for Monitoring User Request Runs that are due but not running
                        // and starting their appropriate process runners
                        thread4.setDaemon(true);
                        thread4.setName("ThreadFour");
                        thread4.setPriority(Thread.MIN_PRIORITY);
                        //System.out.println("Starting ThreadFour thread...");
                        thread4.start();

                        //Thread for Generating Run Requests for Scheduled Alerts
                        thread7 = new MntrSchdldAlertsNtRnngfunc("ThreadSeven");
                        thread7.setDaemon(true);
                        thread7.setName("ThreadSeven");
                        thread7.setPriority(Thread.MIN_PRIORITY);
                        //System.out.println("Starting ThreadSeven thread...");
                        thread7.start();

                        //Thread for Running Requests for User Initiated Alerts
                        thread8 = new MntrUserAlertsNtRnngfunc("ThreadEight");
                        thread8.setDaemon(true);
                        thread8.setName("ThreadEight");
                        thread8.setPriority(Thread.MIN_PRIORITY);
                        //System.out.println("Starting ThreadEight thread...");
                        thread8.start();
                    }
                } else {
                    //Thread for running the actual Code behind the Request Run if this is the
                    //Program supposed to run that request
                    //i.e. if Global.runID >0
                    Global.minimizeMemory();
                    if (Global.runID > 0) {
                        thread1 = new RqstLstnrUpdtrfunc("ThreadOne");
                        thread1.setDaemon(true);
                        thread1.setName("ThreadOne");
                        thread1.setPriority(Thread.MIN_PRIORITY);
                        //System.out.println("Starting ThreadOne thread...");
                        thread1.start();

                        thread5 = new RunActualRqtsfunc("ThreadFive");
                        thread5.setDaemon(true);
                        thread5.setName("ThreadFive");
                        //System.out.println("Starting ThreadFive thread...");
                        if (rnnPryty.equals("1-Highest")) {
                            thread1.setPriority(Thread.MAX_PRIORITY);
                        } else if (rnnPryty.equals("2-AboveNormal")) {
                            thread1.setPriority(7);
                        } else if (rnnPryty.equals("3-Normal")) {
                            thread1.setPriority(Thread.NORM_PRIORITY);
                        } else if (rnnPryty.equals("4-BelowNormal")) {
                            thread1.setPriority(3);
                        } else {
                            thread1.setPriority(1);
                        }
                        thread5.start();
                    }
                    // Allow counting for 10 seconds.
                    //Thread.Sleep(1000);
                }
            }
        }
    } catch (NumberFormatException ex) {
        Global.errorLog = ex.getMessage() + System.getProperty("line.separator")
                + Arrays.toString(ex.getStackTrace());
        String fileLoc = Global.rnnrsBasDir + "/log_files/";
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("ddMMMyyyyHHmmss");
        fileLoc += "Global.errorLog" + ft.format(dNow.getTime()) + ".rho";
        PrintWriter fileWriter;
        try {
            fileWriter = new PrintWriter(fileLoc, "UTF-8");
            fileWriter.println(Global.errorLog);
            fileWriter.close();
        } catch (FileNotFoundException ex1) {
            Logger.getLogger(Program.class.getName()).log(Level.SEVERE, null, ex1);
        } catch (UnsupportedEncodingException ex1) {
            Logger.getLogger(Program.class.getName()).log(Level.SEVERE, null, ex1);
        }
        killThreads();
    } catch (SQLException ex) {
        Global.errorLog = ex.getMessage() + System.getProperty("line.separator")
                + Arrays.toString(ex.getStackTrace());
        String fileLoc = Global.rnnrsBasDir + "/log_files/";
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("ddMMMyyyyHHmmss");
        fileLoc += "Global.errorLog" + ft.format(dNow.getTime()) + ".rho";
        PrintWriter fileWriter;
        try {
            fileWriter = new PrintWriter(fileLoc, "UTF-8");
            fileWriter.println(Global.errorLog);
            fileWriter.close();
        } catch (FileNotFoundException ex1) {
            Logger.getLogger(Program.class.getName()).log(Level.SEVERE, null, ex1);
        } catch (UnsupportedEncodingException ex1) {
            Logger.getLogger(Program.class.getName()).log(Level.SEVERE, null, ex1);
        }
        killThreads();
    } finally {

    }
}

From source file:com.griddynamics.jagger.JaggerLauncher.java

public static void main(String[] args) throws Exception {
    Thread memoryMonitorThread = new Thread("memory-monitor") {
        @Override/*from  ww w. ja  va2 s  .  co  m*/
        public void run() {
            for (;;) {
                try {
                    log.info("Memory info: totalMemory={}, freeMemory={}", Runtime.getRuntime().totalMemory(),
                            Runtime.getRuntime().freeMemory());

                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };
    memoryMonitorThread.setDaemon(true);
    memoryMonitorThread.start();

    String pid = ManagementFactory.getRuntimeMXBean().getName();
    System.out.println(String.format("PID:%s", pid));

    Properties props = System.getProperties();
    for (Map.Entry<Object, Object> prop : props.entrySet()) {
        log.info("{}: '{}'", prop.getKey(), prop.getValue());
    }
    log.info("");

    URL directory = new URL("file:" + System.getProperty("user.dir") + "/");
    loadBootProperties(directory, args[0], environmentProperties);

    log.debug("Bootstrap properties:");
    for (String propName : environmentProperties.stringPropertyNames()) {
        log.debug("   {}={}", propName, environmentProperties.getProperty(propName));
    }

    String[] roles = environmentProperties.getProperty(ROLES).split(",");
    Set<String> rolesSet = Sets.newHashSet(roles);

    if (rolesSet.contains(Role.COORDINATION_SERVER.toString())) {
        launchCoordinationServer(directory);
    }
    if (rolesSet.contains(Role.HTTP_COORDINATION_SERVER.toString())) {
        launchCometdCoordinationServer(directory);
    }
    if (rolesSet.contains(Role.RDB_SERVER.toString())) {
        launchRdbServer(directory);
    }
    if (rolesSet.contains(Role.MASTER.toString())) {
        launchMaster(directory);
    }
    if (rolesSet.contains(Role.KERNEL.toString())) {
        launchKernel(directory);
    }

    if (rolesSet.contains(Role.REPORTER.toString())) {
        launchReporter(directory);
    }

    LaunchManager launchManager = builder.build();

    int result = launchManager.launch();

    System.exit(result);

}

From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorker.java

public static void main(String[] args) {
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

    ////w w  w  .ja  va2s. c  om
    // Get name representing the running Java virtual machine.
    // It returns something like 6460@AURORA. Where the value
    // before the @ symbol is the PID.
    //
    String jvmName = bean.getName();

    //Used for log4j properties
    System.setProperty("logfile.name", "worker" + jvmName);

    //Used for log4j properties
    System.setProperty("steplog.name", "workerStep" + jvmName);

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_SS");
    Date date = new Date();
    dateFormat.format(date);

    System.setProperty("timestamp", date.toLocaleString());

    System.setProperty("paramsfile.name", "params");
    try {
        File logPath = new File("Logs/workers");
        if (logPath.exists())
            FileUtils.cleanDirectory(logPath);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger = Logger.getLogger(DMasonWorker.class.getCanonicalName());
    logger.debug("StartWorker " + version);

    autoStart = false;
    connect = false;
    ip = null;
    port = null;
    String topic = "";
    updated = false;
    isBatch = false;
    topicPrefix = "";

    if (args.length == 0) {
        // Force waiting for beacon (requires ActiveMQWrapper)
        autoStart = false;
        connect = true;
    } else if (args.length == 2) {
        // Launched with IP and Port
        ip = args[0];
        port = args[1];
        autoStart = true;
        connect = true;
    } else if (args.length == 4) {
        // Used by D-Mason in order to restart a 
        // worker after update, batch execution, reset
        autoStart = true;
        ip = args[0];
        port = args[1];
        topic = args[2];
        if (args[3].equals("update")) {
            updated = true;
        }
        if (args[3].equals("reset")) {
            updated = false;
            isBatch = false;
        }
        if (args[3].contains("Batch")) {
            updated = false;
            isBatch = true;
            topicPrefix = args[3];
        }
    } else {
        System.out.println("Usage: StartWorker IP PORT");
    }

    DMasonWorker worker = new DMasonWorker(ip, port, topic);

    boolean connected = worker.startConnection();

    if (connected) {
        logger.debug("CONNECTED:");
        logger.debug("   IP     : " + worker.ipAddress.getIPaddress());
        logger.debug("   Port   : " + worker.ipAddress.getPort());
        logger.debug("   Prefix : " + DMasonWorker.topicPrefix);
        logger.debug("   Topic  : " + worker.myTopic);
    } else {
        logger.info("CONNECTION FAILED:");
        logger.debug("   IP     : " + worker.ipAddress.getIPaddress());
        logger.debug("   Port   : " + worker.ipAddress.getPort());
        logger.debug("   Prefix : " + DMasonWorker.topicPrefix);
        logger.debug("   Topic  : " + worker.myTopic);
    }
}

From source file:com.evolveum.midpoint.web.boot.MidPointSpringApplication.java

public static void main(String[] args) {
    System.setProperty("xml.catalog.className", CatalogImpl.class.getName());
    String mode = args != null && args.length > 0 ? args[0] : null;

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("PID:" + ManagementFactory.getRuntimeMXBean().getName() + " Application mode:" + mode
                + " context:" + applicationContext);
    }/*from w w w  .j a v  a2 s. c o m*/

    if (applicationContext != null && mode != null && "stop".equals(mode)) {
        System.exit(SpringApplication.exit(applicationContext, new ExitCodeGenerator() {

            @Override
            public int getExitCode() {

                return 0;
            }
        }));

    } else {

        applicationContext = configureApplication(new SpringApplicationBuilder()).run(args);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("PID:" + ManagementFactory.getRuntimeMXBean().getName()
                    + " Application started context:" + applicationContext);
        }

    }

}

From source file:hdfs.MiniHDFS.java

public static void main(String[] args) throws Exception {
    if (args.length != 1 && args.length != 3) {
        throw new IllegalArgumentException(
                "Expected: MiniHDFS <baseDirectory> [<kerberosPrincipal> <kerberosKeytab>], " + "got: "
                        + Arrays.toString(args));
    }//from  w  w w. j a v  a  2 s  .  c  om
    boolean secure = args.length == 3;

    // configure Paths
    Path baseDir = Paths.get(args[0]);
    // hadoop-home/, so logs will not complain
    if (System.getenv("HADOOP_HOME") == null) {
        Path hadoopHome = baseDir.resolve("hadoop-home");
        Files.createDirectories(hadoopHome);
        System.setProperty("hadoop.home.dir", hadoopHome.toAbsolutePath().toString());
    }
    // hdfs-data/, where any data is going
    Path hdfsHome = baseDir.resolve("hdfs-data");

    // configure cluster
    Configuration cfg = new Configuration();
    cfg.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsHome.toAbsolutePath().toString());
    // lower default permission: TODO: needed?
    cfg.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_PERMISSION_KEY, "766");

    // optionally configure security
    if (secure) {
        String kerberosPrincipal = args[1];
        String keytabFile = args[2];

        cfg.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
        cfg.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, "true");
        cfg.set(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_DATANODE_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY, keytabFile);
        cfg.set(DFSConfigKeys.DFS_DATANODE_KEYTAB_FILE_KEY, keytabFile);
        cfg.set(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, "true");
        cfg.set(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, "true");
        cfg.set(DFSConfigKeys.IGNORE_SECURE_PORTS_FOR_TESTING_KEY, "true");
    }

    UserGroupInformation.setConfiguration(cfg);

    // TODO: remove hardcoded port!
    MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(cfg);
    if (secure) {
        builder.nameNodePort(9998);
    } else {
        builder.nameNodePort(9999);
    }
    MiniDFSCluster dfs = builder.build();

    // Configure contents of the filesystem
    org.apache.hadoop.fs.Path esUserPath = new org.apache.hadoop.fs.Path("/user/elasticsearch");
    try (FileSystem fs = dfs.getFileSystem()) {

        // Set the elasticsearch user directory up
        fs.mkdirs(esUserPath);
        if (UserGroupInformation.isSecurityEnabled()) {
            List<AclEntry> acls = new ArrayList<>();
            acls.add(new AclEntry.Builder().setType(AclEntryType.USER).setName("elasticsearch")
                    .setPermission(FsAction.ALL).build());
            fs.modifyAclEntries(esUserPath, acls);
        }

        // Install a pre-existing repository into HDFS
        String directoryName = "readonly-repository";
        String archiveName = directoryName + ".tar.gz";
        URL readOnlyRepositoryArchiveURL = MiniHDFS.class.getClassLoader().getResource(archiveName);
        if (readOnlyRepositoryArchiveURL != null) {
            Path tempDirectory = Files.createTempDirectory(MiniHDFS.class.getName());
            File readOnlyRepositoryArchive = tempDirectory.resolve(archiveName).toFile();
            FileUtils.copyURLToFile(readOnlyRepositoryArchiveURL, readOnlyRepositoryArchive);
            FileUtil.unTar(readOnlyRepositoryArchive, tempDirectory.toFile());

            fs.copyFromLocalFile(true, true,
                    new org.apache.hadoop.fs.Path(
                            tempDirectory.resolve(directoryName).toAbsolutePath().toUri()),
                    esUserPath.suffix("/existing/" + directoryName));

            FileUtils.deleteDirectory(tempDirectory.toFile());
        }
    }

    // write our PID file
    Path tmp = Files.createTempFile(baseDir, null, null);
    String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    Files.write(tmp, pid.getBytes(StandardCharsets.UTF_8));
    Files.move(tmp, baseDir.resolve(PID_FILE_NAME), StandardCopyOption.ATOMIC_MOVE);

    // write our port file
    tmp = Files.createTempFile(baseDir, null, null);
    Files.write(tmp, Integer.toString(dfs.getNameNodePort()).getBytes(StandardCharsets.UTF_8));
    Files.move(tmp, baseDir.resolve(PORT_FILE_NAME), StandardCopyOption.ATOMIC_MOVE);
}

From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorkerWithGui.java

public static void main(String[] args) {
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

    ///*from  w  w w.ja v a2s .  c  o  m*/
    // Get name representing the running Java virtual machine.
    // It returns something like 6460@AURORA. Where the value
    // before the @ symbol is the PID.
    //
    String jvmName = bean.getName();

    //Used for log4j properties
    System.setProperty("logfile.name", "worker" + jvmName);

    //Used for log4j properties
    System.setProperty("steplog.name", "workerStep" + jvmName);

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_SS");
    Date date = new Date();
    dateFormat.format(date);

    System.setProperty("timestamp", date.toLocaleString());

    System.setProperty("paramsfile.name", "params");
    try {
        File logPath = new File("Logs/workers");
        if (logPath.exists())
            FileUtils.cleanDirectory(logPath);
    } catch (IOException e) {
        //not a problem
    }

    logger = Logger.getLogger(DMasonWorker.class.getCanonicalName());
    logger.debug("StartWorker " + VERSION);

    autoStart = false;

    String ip = null;
    String port = null;
    String topic = "";
    updated = false;
    isBatch = false;
    topicPrefix = "";

    // ip, post, autoconnect
    if (args.length == 3) {
        ip = args[0];
        port = args[1];
        if (args[2].equals("autoconnect")) {
            autoStart = true;
        }
    }
    // ip, post, topic, event 
    if (args.length == 4) {
        autoStart = true;
        if (args[3].equals("update")) {
            updated = true;
        }
        if (args[3].equals("reset")) {
            updated = false;
            isBatch = false;
        }
        if (args[3].contains("Batch")) {
            updated = false;
            isBatch = true;
            topicPrefix = args[3];
        }
        ip = args[0];
        port = args[1];
        topic = args[2];
    }

    /*if(args.length == 2 && args[0].equals("auto"))
    {   autoStart = true;
       updated = true;
       topic = args[1];
    }
    if(args.length == 1 && args[0].equals("auto"))
    {   autoStart = true;
    }*/
    new DMasonWorkerWithGui(autoStart, updated, isBatch, topic, ip, port);
}

From source file:Main.java

public static long getPid() {
    RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
    String[] mxNameTable = mx.getName().split("@"); //$NON-NLS-1$
    if (mxNameTable.length == 2) {
        return Long.parseLong(mxNameTable[0]);
    } else {//  www . j  a v a2  s  .  c  o  m
        return Thread.currentThread().getId();
    }
}

From source file:org.apache.hadoop.hbase.io.BatchUpdate.java

/**
 * Code to test sizes of BatchUpdate arrays.
 * @param args//  w  ww.ja  va  2  s.  com
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    LOG.info("vmName=" + runtime.getVmName() + ", vmVendor=" + runtime.getVmVendor() + ", vmVersion="
            + runtime.getVmVersion());
    LOG.info("vmInputArguments=" + runtime.getInputArguments());
    final int count = 10000;
    BatchUpdate[] batch1 = new BatchUpdate[count];
    // TODO: x32 vs x64
    long size = 0;
    for (int i = 0; i < count; i++) {
        BatchUpdate bu = new BatchUpdate(HConstants.EMPTY_BYTE_ARRAY);
        bu.put(HConstants.EMPTY_BYTE_ARRAY, HConstants.EMPTY_BYTE_ARRAY);
        batch1[i] = bu;
        size += bu.heapSize();
    }
    LOG.info("batch1 estimated size=" + size);
    // Make a variably sized memcache.
    size = 0;
    BatchUpdate[] batch2 = new BatchUpdate[count];
    for (int i = 0; i < count; i++) {
        BatchUpdate bu = new BatchUpdate(Bytes.toBytes(i));
        bu.put(Bytes.toBytes(i), new byte[i]);
        batch2[i] = bu;
        size += bu.heapSize();
    }
    LOG.info("batch2 estimated size=" + size);
    final int seconds = 30;
    LOG.info("Waiting " + seconds + " seconds while heap dump is taken");
    for (int i = 0; i < seconds; i++) {
        Thread.sleep(1000);
    }
    LOG.info("Exiting.");
}

From source file:com.kotcrab.vis.editor.util.ApplicationUtils.java

public static String getRestartCommand() {
    List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
    StringBuilder vmArgsOneLine = new StringBuilder();

    if (OsUtils.isMac()) {
        vmArgsOneLine.append("-XstartOnFirstThread ");
    }/*from w  ww .  j a va  2 s. c om*/

    for (String arg : vmArguments) {
        if (arg.contains("-agentlib") == false) {
            vmArgsOneLine.append(arg).append(" ");
        }
    }

    final StringBuilder cmd = new StringBuilder(PlatformUtils.getJavaBinPath() + " " + vmArgsOneLine);

    String[] mainCommand = System.getProperty("sun.java.command").split(" ");

    if (mainCommand[0].endsWith(".jar"))
        cmd.append("-jar " + new File(mainCommand[0]).getPath());
    else
        cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);

    for (int i = 1; i < mainCommand.length; i++) {
        cmd.append(" ");
        cmd.append(mainCommand[i]);
    }

    //if launching from idea, not in debug mode
    String ideaLauncher = "-Didea.launcher.bin.path=";
    int ideaLauncherStart = cmd.indexOf(ideaLauncher);
    if (ideaLauncherStart != -1) {
        cmd.insert(ideaLauncherStart + ideaLauncher.length(), "\"");
        cmd.insert(cmd.indexOf("-cp ", ideaLauncherStart) - 1, "\"");
    }

    return cmd.toString();
}

From source file:org.springframework.boot.util.SystemUtils.java

/**
 * Looks for application PID//from   w  ww  .j a va2 s.  c o  m
 * @return application PID
 * @throws java.lang.IllegalStateException if PID could not be determined
 */
public static String getApplicationPid() {
    String pid = null;
    try {
        RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        String jvmName = runtimeBean.getName();
        if (StringUtils.isEmpty(jvmName)) {
            LOG.warn("Cannot get JVM name");
        }
        if (!jvmName.contains("@")) {
            LOG.warn("JVM name doesn't contain process id");
        }
        pid = jvmName.split("@")[0];
    } catch (Throwable e) {
        LOG.warn("Cannot get RuntimeMXBean", e);
    }

    if (pid == null) {
        throw new IllegalStateException("Application PID not found");
    }

    return pid;
}