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:org.pepstock.jem.gwt.server.SubmitManagerServiceImpl.java

@Override
public String loaded(List<FileItem> items) throws JemException {
    try {//from   w w w.  ja  v  a 2s  .c  o  m
        JobsManager jobsManager = new JobsManager();

        String fileName = null;
        PreJob preJob = null;
        // scans all files uploaded
        for (FileItem item : items) {
            // works only with field of JEM
            // other files are ignored
            if (item.getFieldName().equalsIgnoreCase(LegacySubmitter.FILE_UPLOAD_FIELD)) {
                // 
                fileName = item.getName();

                // reads file uploaded
                StringWriter writer = new StringWriter();
                IOUtils.copy(item.getInputStream(), writer);
                // creates a PreJob to submit
                // sets JCL content
                preJob = new PreJob();
                preJob.setJclContent(writer.toString());

                // creates a empty job
                Job job = new Job();
                // loads all line arguments (the -D properties).
                // could be useful to factories, listeners and during
                // job execution to
                // job itself
                job.setInputArguments(ManagementFactory.getRuntimeMXBean().getInputArguments());
                // uses file name as job name
                job.setName(fileName);

                // loads prejob with job
                preJob.setJob(job);
            } else if (item.getFieldName().equalsIgnoreCase(LegacySubmitter.TYPE_FIELD)) {
                // reads JCl type
                String type = item.getString();
                // sets JCL type which was an argument
                preJob.setJclType(type);
            }
        }

        // if prejob is not instantiated means jcl file are not set
        if (preJob != null) {
            String id;
            // submits JOB and get job it to return
            id = jobsManager.submit(preJob);
            return UserInterfaceMessage.JEMG034I.toMessage().getFormattedMessage(fileName, id);
        } else {
            throw new JemException(UserInterfaceMessage.JEMG035E.toMessage().getFormattedMessage());
        }
    } catch (ServiceMessageException e) {
        LogAppl.getInstance().emit(UserInterfaceMessage.JEMG048E, e);
        throw new JemException(UserInterfaceMessage.JEMG048E.toMessage().getFormattedMessage(e.getMessage()));
    } catch (IOException e) {
        LogAppl.getInstance().emit(UserInterfaceMessage.JEMG048E, e);
        throw new JemException(UserInterfaceMessage.JEMG048E.toMessage().getFormattedMessage(e.getMessage()));
    }
}

From source file:org.springframework.xd.dirt.container.DefaultContainer.java

@Override
public String getJvmName() {
    synchronized (this) {
        if (this.jvmName == null) {
            this.jvmName = ManagementFactory.getRuntimeMXBean().getName();
        }//from  w  ww.  j  a v a 2s. c  o  m
    }
    return this.jvmName;
}

From source file:com.jkoolcloud.tnt4j.utils.Utils.java

private static long initVMID() {
    String _vm_pid_del = System.getProperty("tnt4j.java.vm.pid.dlm", "@");
    String vm_name = ManagementFactory.getRuntimeMXBean().getName();
    try {/*  w ww. j  a  va 2  s .c  om*/
        int index = vm_name.indexOf(_vm_pid_del);
        if (index > 0) {
            return Long.parseLong(vm_name.substring(0, index));
        }
    } catch (Throwable e) {
    }
    return 0;
}

From source file:org.janusgraph.graphdb.idmanagement.UniqueInstanceIdRetriever.java

private String getSuffix(Configuration config) {
    final String suffix;
    if (config.has(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID_SUFFIX)) {
        suffix = LongEncoding.encode(config.get(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID_SUFFIX));
    } else if (!config.has(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID_HOSTNAME)) {
        suffix = ManagementFactory.getRuntimeMXBean().getName()
                + LongEncoding.encode(instanceCounter.incrementAndGet());
    } else {//from  ww  w .java 2s  .c o  m
        suffix = "";
    }
    return suffix;
}

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

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

From source file:org.apache.flink.runtime.util.EnvironmentInformation.java

public static String getJvmStartupOptions() {
    try {//www  . j a v a 2s  .  c  o m
        final RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
        final StringBuilder bld = new StringBuilder();
        for (String s : bean.getInputArguments()) {
            if (!s.startsWith(LOG_FILE_OPTION) && !s.startsWith(LOG_CONFIGURAION_OPTION)) {
                bld.append(s).append(' ');
            }
        }
        return bld.toString();
    } catch (Throwable t) {
        return UNKNOWN;
    }
}

From source file:gobblin.kafka.writer.Kafka08DataWriterIntegrationTest.java

@Test
public void testErrors() throws Exception {
    log.warn("Process id = " + ManagementFactory.getRuntimeMXBean().getName());
    int numRecordsPerExtract = 5;
    int numParallel = 2;
    int errorEvery = 2000;
    int totalRecords = numRecordsPerExtract * numParallel;
    int totalSuccessful = totalRecords / errorEvery + totalRecords % errorEvery;
    {/*from  w  w w.j  av  a  2s  .  co m*/
        Closer closer = Closer.create();

        try {

            kafkaTestHelper.provisionTopic(TOPIC);
            jobProps.setProperty("source.numRecordsPerExtract", "" + numRecordsPerExtract);
            jobProps.setProperty("source.numParallelism", "" + numParallel);
            jobProps.setProperty("writer.kafka.producerConfig.flaky.errorType", "regex");
            // all records from partition 0 will be dropped.
            jobProps.setProperty("writer.kafka.producerConfig.flaky.regexPattern", ":index:0.*");
            jobProps.setProperty("job.commit.policy", "partial");
            jobProps.setProperty("publish.at.job.level", "false");
            totalSuccessful = 5; // number of records in partition 1
            JobLauncher jobLauncher = closer
                    .register(JobLauncherFactory.newJobLauncher(gobblinProps, jobProps));
            jobLauncher.launchJob(null);
        } catch (Exception e) {
            log.error("Failed to run job with exception ", e);
            Assert.fail("Should not throw exception on running the job");
        } finally {
            closer.close();
        }
        // test records written

        testRecordsWritten(totalSuccessful, TOPIC);
    }
    boolean trySecond = true;
    if (trySecond) {
        Closer closer = Closer.create();
        try {
            jobProps.setProperty("source.numRecordsPerExtract", "" + numRecordsPerExtract);
            jobProps.setProperty("source.numParallelism", "" + numParallel);
            jobProps.setProperty("writer.kafka.producerConfig.flaky.errorType", "nth");
            jobProps.setProperty("writer.kafka.producerConfig.flaky.errorEvery", "" + errorEvery);
            JobLauncher jobLauncher = closer
                    .register(JobLauncherFactory.newJobLauncher(gobblinProps, jobProps));
            jobLauncher.launchJob(null);
            totalSuccessful = totalRecords / errorEvery + totalRecords % errorEvery;
        } catch (Exception e) {
            log.error("Failed to run job with exception ", e);
            Assert.fail("Should not throw exception on running the job");
        } finally {
            closer.close();
        }
    }

    // test records written
    testRecordsWritten(totalSuccessful, TOPIC);

}

From source file:org.zenoss.app.metric.zapp.ManagedReporter.java

@PostConstruct
public void init() throws Exception {
    Map<String, String> tags = Maps.newHashMap();
    tags.put("zapp", environment.getName());
    tags.put("daemon", environment.getName());
    tags.put("host", getHostTag());
    tags.put("instance", ManagementFactory.getRuntimeMXBean().getName());
    tags.put("internal", "true");

    MetricPredicate predicate = filter;//from w  w  w  . j  av a  2  s  .c o m
    if (predicate == null) {
        predicate = MetricPredicate.ALL;
    }

    // include all posters defined in configuration
    for (MetricReporterConfig config : getManagedReporterConfig().getMetricReporters()) {
        MetricPoster poster = getPoster(config);
        if (poster != null) {
            ZenossMetricsReporter reporter = buildMetricReporter(config, poster, predicate, tags);
            metricReporters.add(reporter);
        } else {
            LOG.info("Unable to build reporter");
        }
    }
}

From source file:net.centro.rtb.monitoringcenter.metrics.system.jvm.GarbageCollectorMetricSet.java

GarbageCollectorMetricSet() {
    this.garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();

    this.minorGcTimer = new Timer();
    this.majorGcTimer = new Timer();

    // Determine the location of the gc log file (note that there's not support for rolling gc logs)
    String gcLogFilePath = null;//from www.j  a va  2  s. c o m
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    List<String> inputArguments = runtimeMXBean.getInputArguments();
    for (String argument : inputArguments) {
        if (argument.startsWith(LOG_GC_JVM_PARAM)) {
            gcLogFilePath = argument.substring(LOG_GC_JVM_PARAM.length());
            break;
        }
    }

    if (gcLogFilePath != null && !gcLogFilePath.trim().isEmpty()) {
        final File gcLogFile = new File(gcLogFilePath);
        if (gcLogFile.exists()) {
            this.fullCollectionsCounter = new AtomicLong();

            this.gcLogTailer = Tailer.create(gcLogFile, new TailerListenerAdapter() {
                @Override
                public void handle(String line) {
                    if (line != null && line.contains(FULL_GC_LOG_STRING)) {
                        fullCollectionsCounter.incrementAndGet();
                    }
                }
            }, GC_LOG_FILE_TAIL_DELAY_IN_MILLIS);
        }
    }

    // Attach a listener to the GarbageCollectorMXBeans
    this.gcEventListener = new NotificationListener() {
        @Override
        public void handleNotification(Notification notification, Object handback) {
            String notificationType = notification.getType();
            if (notificationType.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                CompositeData compositeData = CompositeData.class.cast(notification.getUserData());
                GarbageCollectionNotificationInfo gcNotificationInfo = GarbageCollectionNotificationInfo
                        .from(compositeData);

                if (GC_NOTIFICATION_MINOR_GC_ACTION_STRING.equals(gcNotificationInfo.getGcAction())) {
                    minorGcTimer.update(gcNotificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                } else if (GC_NOTIFICATION_MAJOR_GC_ACTION_STRING.equals(gcNotificationInfo.getGcAction())) {
                    majorGcTimer.update(gcNotificationInfo.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);
                }
            }
        }
    };

    for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        if (NotificationEmitter.class.isInstance(garbageCollectorMXBean)) {
            NotificationEmitter emitter = NotificationEmitter.class.cast(garbageCollectorMXBean);
            emitter.addNotificationListener(gcEventListener, null, null);
        }
    }

    // Set up metrics
    Map<String, Metric> metricsByNames = new HashMap<>();

    if (fullCollectionsCounter != null) {
        this.fullCollectionsGauge = new Gauge<Long>() {
            @Override
            public Long getValue() {
                return fullCollectionsCounter.get();
            }
        };
        metricsByNames.put("fullCollections", fullCollectionsGauge);
    }

    metricsByNames.put("majorGcTimer", majorGcTimer);
    metricsByNames.put("minorGcTimer", minorGcTimer);

    List<GarbageCollectorStatus> garbageCollectorStatuses = new ArrayList<>();
    for (final GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        final String garbageCollectorName = garbageCollectorMXBean.getName();
        final String garbageCollectorNamespace = MetricNamingUtil.join("collectors",
                MetricNamingUtil.sanitize(garbageCollectorName));

        final Gauge<Long> collectionsGauge;
        if (garbageCollectorMXBean.getCollectionCount() >= 0) {
            collectionsGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return garbageCollectorMXBean.getCollectionCount();
                }
            };
            metricsByNames.put(MetricNamingUtil.join(garbageCollectorNamespace, "collections"),
                    collectionsGauge);
        } else {
            collectionsGauge = null;
        }

        final Gauge<Long> totalCollectionDurationInMillisGauge;
        if (garbageCollectorMXBean.getCollectionTime() >= 0) {
            totalCollectionDurationInMillisGauge = new Gauge<Long>() {
                @Override
                public Long getValue() {
                    return garbageCollectorMXBean.getCollectionTime();
                }
            };
            metricsByNames.put(
                    MetricNamingUtil.join(garbageCollectorNamespace, "totalCollectionDurationInMillis"),
                    totalCollectionDurationInMillisGauge);
        } else {
            totalCollectionDurationInMillisGauge = null;
        }

        garbageCollectorStatuses.add(new GarbageCollectorStatus() {
            @Override
            public String getName() {
                return garbageCollectorName;
            }

            @Override
            public Gauge<Long> getCollectionsGauge() {
                return collectionsGauge;
            }

            @Override
            public Gauge<Long> getTotalCollectionDurationInMillisGauge() {
                return totalCollectionDurationInMillisGauge;
            }
        });
    }
    this.garbageCollectorStatuses = garbageCollectorStatuses;

    this.metricsByNames = metricsByNames;
}

From source file:org.sourceopen.hadoop.zookeeper.connect.RecoverableZooKeeper.java

RecoverableZooKeeper(String quorumServers, int seesionTimeout, Watcher watcher, int maxRetries,
        int retryIntervalMillis) throws IOException {
    this.zk = new ZooKeeper(quorumServers, seesionTimeout, watcher);
    this.retryCounterFactory = new RetryCounterFactory(maxRetries, retryIntervalMillis);
    this.retryIntervalMillis = retryIntervalMillis;

    // the identifier = processID@hostName
    this.identifier = ManagementFactory.getRuntimeMXBean().getName();
    LOG.info("The identifier of this process is " + identifier);
    this.id = Bytes.toBytes(identifier);
}