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:itinno.example.ExampleSocialMediaJavaLoggerBolt.java

/**
 * Prepare method is similar the "Open" method for Spouts and is called when a worker is about to be put to work.
 * This method also initialise the main example Storm Java bolt logger.
 * //from  w w  w .  java 2s . c  o m
 * @param stormConf  map of the storm configuration (passed within Storm topology itself, not be a user)
 * @param context    context (e.g. similar to description) of the topology (passed within Storm topology itself, not be a user)
 * @param collector  output collector of the Storm (which is responsible to emiting new tuples, passed within Storm topology itself, not be a user)
 */
@Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
    String strPID = null;
    this.collector = collector;

    // Setup the logger
    try {
        // Create log file name - combination of class name and current PID e.g. ExampleJavaSocialMediaStormTopologyRunner_pid123.log
        try {
            // Try to get the pid using java.lang.Management class and split it on @ symbol (e.g. returned value will be in the format of {p_id}@{host_name})
            strPID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];

            // Handle any possible exception here, such as if the process_name@host will not be returned (possible, depends on different JVMs)
        } catch (Exception e) {
            // Print the message, stacktrace and allow to continue (pid value will not be contained in the log file)
            System.err.println(
                    "Failed to get process process id. Will continue but the log files names will not contain pid value. Details: "
                            + e.getMessage());
            e.printStackTrace();

            // Pid will be simply an empty value
            strPID = "";
        }

        // Create log file name - combination of class name and current process id, e.g. ExampleSocialMediaJavaLoggerBolt_pid123.log 
        String strLogName = "ExampleSocialMediaJavaLoggerBolt_pid" + strPID + ".log";

        // Specify the path to the log file (the file that will be created)
        String fileSep = System.getProperty("file.separator");
        String strLogFilePath = this.strLogBaseDir + fileSep + strLogName;

        StormLoggingHelper stormLoggingHelper = new StormLoggingHelper();
        this.logger = stormLoggingHelper.createLogger(ExampleSocialMediaJavaLoggerBolt.class.getName(),
                strLogFilePath, this.strLogPattern, this.logLevel);

        // Issue test message
        this.logger.info("Logger was initialised.");

    } catch (Exception e) {
        // Print error message, stacktrace and throw an exception since the log functionality is the main target of this bolt 
        System.err.printf(
                "Error occurred during Storm Java Logger Bolt logger setup. Details: " + e.getMessage());
        e.printStackTrace();
        try {
            throw new Exception("Java Storm logger bolt log initialisation failed. Details: " + e.getMessage());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}

From source file:com.h3xstream.findbugs.test.BaseDetectorTest.java

@AfterClass
public void after() {
    System.gc();// w  ww. j  a  v a  2 s . co m
    if (DEBUG) {
        Runtime rt = Runtime.getRuntime();
        long inMb = 1024 * 1024;
        log.info("=== Memory info (Process " + ManagementFactory.getRuntimeMXBean().getName() + ") ===");
        log.info("Total memory : " + rt.totalMemory() / inMb);
        log.info("Free memory  : " + rt.freeMemory() / inMb);
        log.info("Memory usage : " + (rt.totalMemory() - rt.freeMemory()) / inMb);
        log.info("===================");
    }

    //        for(Object mock : mocksToReset) {
    //            reset(mock);
    //        }
    //        mocksToReset.clear();
}

From source file:org.apache.hadoop.hbase.util.JSONMetricUtil.java

public static String getProcessPID() {
    return ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
}

From source file:com.amazonaws.services.simpleworkflow.flow.worker.GenericWorker.java

public GenericWorker() {
    identity = ManagementFactory.getRuntimeMXBean().getName();
    int length = Math.min(identity.length(), GenericWorker.MAX_IDENTITY_LENGTH);
    identity = identity.substring(0, length);
}

From source file:org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper.java

public RecoverableZooKeeper(String quorumServers, int sessionTimeout, Watcher watcher, int maxRetries,
        int retryIntervalMillis, String identifier) throws IOException {
    // TODO: Add support for zk 'chroot'; we don't add it to the quorumServers String as we should.
    this.zk = new ZooKeeper(quorumServers, sessionTimeout, watcher);
    this.retryCounterFactory = new RetryCounterFactory(maxRetries + 1, retryIntervalMillis);

    if (identifier == null || identifier.length() == 0) {
        // the identifier = processID@hostName
        identifier = ManagementFactory.getRuntimeMXBean().getName();
    }// w  w  w  .  java 2s. c  o  m
    LOG.info("Process identifier=" + identifier + " connecting to ZooKeeper ensemble=" + quorumServers);
    this.identifier = identifier;
    this.id = Bytes.toBytes(identifier);

    this.watcher = watcher;
    this.sessionTimeout = sessionTimeout;
    this.quorumServers = quorumServers;
    salter = new SecureRandom();
}

From source file:org.yamj.common.model.YamjInfo.java

public String getUptime() {
    return DateTimeTools.formatDurationText(ManagementFactory.getRuntimeMXBean().getUptime());
}

From source file:org.apache.hadoop.hbase.util.JSONMetricUtil.java

public static String getCommmand() throws MalformedObjectNameException, IOException, JSONException {
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    return runtimeBean.getSystemProperties().get("sun.java.command");
}

From source file:com.netflix.explorers.AppConfigGlobalModelContext.java

@Override
public long getStartTime() {
    RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
    return rb.getStartTime();
}

From source file:org.apache.hadoop.yarn.server.sharedcachemanager.CleanerService.java

/**
 * To ensure there are not multiple instances of the SCM running on a given
 * cluster, a global pid file is used. This file contains the hostname of the
 * machine that owns the pid file.//ww  w. j  a  v a 2  s.  c  o m
 *
 * @return true if the pid file was written, false otherwise
 * @throws YarnException
 */
private boolean writeGlobalCleanerPidFile() throws YarnException {
    String root = conf.get(YarnConfiguration.SHARED_CACHE_ROOT, YarnConfiguration.DEFAULT_SHARED_CACHE_ROOT);
    Path pidPath = new Path(root, GLOBAL_CLEANER_PID);
    try {
        FileSystem fs = FileSystem.get(this.conf);

        if (fs.exists(pidPath)) {
            return false;
        }

        FSDataOutputStream os = fs.create(pidPath, false);
        // write the hostname and the process id in the global cleaner pid file
        final String ID = ManagementFactory.getRuntimeMXBean().getName();
        os.writeUTF(ID);
        os.close();
        // add it to the delete-on-exit to ensure it gets deleted when the JVM
        // exits
        fs.deleteOnExit(pidPath);
    } catch (IOException e) {
        throw new YarnException(e);
    }
    LOG.info("Created the global cleaner pid file at " + pidPath.toString());
    return true;
}

From source file:uk.org.cinquin.mutinack.tests.FunctionalTestRerun.java

@Test
public void test() throws InterruptedException, IOException {
    if (run == null) {
        run = testRuns.get(testName);//from ww  w .j  a  v  a 2  s . co  m
        //TODO Switch to throwing TestRunFailure
        Assert.isNonNull(run, "Could not find parameters for test %s within %s", testName,
                testRuns.keySet().stream().collect(Collectors.joining("\t")));
        Assert.isNonNull(run.parameters.referenceOutput, "No reference output specified for test GenericTest");
        run.parameters.terminateImmediatelyUponError = false;
        if (suppressAlignmentOutput) {
            run.parameters.outputAlignmentFile = Collections.emptyList();
        }
    }

    String referenceOutputDirectory = new File(run.parameters.referenceOutput).getParent();

    final boolean useCustomScript;
    if (new File(referenceOutputDirectory + "/custom_check_script").exists()) {
        useCustomScript = true;
    } else {
        useCustomScript = false;
        Assert.isTrue(new File(run.parameters.referenceOutput).exists(), "File %s does not exist",
                new File(run.parameters.referenceOutput).getAbsolutePath());
    }

    Path referenceOutputPath = Paths.get(run.parameters.referenceOutput);
    String auxOutputFileBaseName = Files.createTempDirectory("functional_test_").toString();
    run.parameters.auxOutputFileBaseName = auxOutputFileBaseName + '/';

    run.parameters.jsonFilePathExtraPrefix = ManagementFactory.getRuntimeMXBean().getName() + this.hashCode();

    try {
        try (ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                ByteArrayOutputStream errStream = new ByteArrayOutputStream()) {

            StaticStuffToAvoidMutating.instantiateThreadPools(64);

            //Only one test should run at a time, so it's OK to use a static variable
            try (PrintStream outPS = new PrintStream(outStream);
                    PrintStream errPS = new PrintStream(errStream)) {
                MutinackGroup.forceKeeperType = duplexKeeperType;
                Mutinack.realMain1(run.parameters, outPS, errPS);
            } finally {
                MutinackGroup.forceKeeperType = null;
            }

            if (useCustomScript) {
                ProcessBuilder pb = new ProcessBuilder("./custom_check_script",
                        run.parameters.jsonFilePathExtraPrefix).directory(new File(referenceOutputDirectory))
                                .redirectErrorStream(true);
                Process process = pb.start();
                try (DataInputStream processOutput = new DataInputStream(process.getInputStream())) {
                    process.waitFor();
                    if (process.exitValue() != 0) {
                        byte[] processBytes = new byte[processOutput.available()];
                        processOutput.readFully(processBytes);
                        throw new FunctionalTestFailed(testName + '\n' + new String(processBytes));
                    }
                }
                return;
            } else {
                final String out = outStream.toString();
                try (Stream<String> referenceOutputLines = Files.lines(referenceOutputPath)) {
                    checkOutput(out, referenceOutputLines);
                }
            }
        }

        File baseOutputDir = referenceOutputPath.getParent().toFile();
        for (String expectedOutputBaseName : baseOutputDir.list((file, name) -> name.startsWith("expected_")
                && !name.equals("expected_run.out") && !name.equals("expected_output.txt"))) {
            File actualOutputFile = new File(
                    auxOutputFileBaseName + '/' + expectedOutputBaseName.replace("expected_", ""));
            if (!actualOutputFile.exists()) {
                throw new FunctionalTestFailed(
                        "Output file " + actualOutputFile.getAbsolutePath() + " was not created");
            }
            //Files.lines needs to be explicitly closed, or else the
            //underlying file does not get closed (apparently even
            //after the stream gets read to the end)
            try (Stream<String> linesToLookFor = Files
                    .lines(Paths.get(baseOutputDir.getAbsolutePath() + '/' + expectedOutputBaseName))) {
                checkOutput(FileUtils.readFileToString(actualOutputFile), linesToLookFor);
            }
        }
    } finally {
        FileUtils.deleteDirectory(new File(auxOutputFileBaseName));
        String prefix = run.parameters.jsonFilePathExtraPrefix;
        if (!prefix.isEmpty()) {
            for (File f : referenceOutputPath.getParent().toFile()
                    .listFiles((dir, name) -> name.startsWith(run.parameters.jsonFilePathExtraPrefix))) {
                f.delete();
            }
        }
    }
}