Example usage for java.lang.management ManagementFactory OPERATING_SYSTEM_MXBEAN_NAME

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

Introduction

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

Prototype

String OPERATING_SYSTEM_MXBEAN_NAME

To view the source code for java.lang.management ManagementFactory OPERATING_SYSTEM_MXBEAN_NAME.

Click Source Link

Document

String representation of the ObjectName for the OperatingSystemMXBean .

Usage

From source file:jsdp.app.control.clqg.univariate.CLQG.java

public static void main(String args[]) {

    /*******************************************************************
     * Problem parameters/*from   w  ww.  j  a va2  s . c  om*/
     */

    int T = 20; // Horizon length
    double G = 1; // Input transition
    double Phi = 1; // State transition
    double R = 1; // Input cost
    double Q = 1; // State cost
    double Ulb = -1; // Action constraint
    double Uub = 20; // Action constraint
    double noiseStd = 5; // Standard deviation of the noise

    double[] noiseStdArray = new double[T];
    Arrays.fill(noiseStdArray, noiseStd);
    double truncationQuantile = 0.975;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(noiseStdArray.length)
            .mapToObj(i -> new NormalDist(0, noiseStdArray[i]))

            .toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(T)
            .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], 1 - truncationQuantile)).toArray();

    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(T)
            .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], truncationQuantile)).toArray();

    double initialX = 0; // Initial state

    /*******************************************************************
     * Model definition
     */

    // State space

    double stepSize = 0.5; //Stepsize must be 1 for discrete distributions
    double minState = -25;
    double maxState = 100;
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = (Function<State, ArrayList<Action>> & Serializable) s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        double maxAction = Math.min(Uub, (StateImpl.getMaxState() - Phi * state.getInitialState()) / G);
        double minAction = Math.max(Ulb, (StateImpl.getMinState() - Phi * state.getInitialState()) / G);
        for (double actionPointer = minAction; actionPointer <= maxAction; actionPointer += StateImpl
                .getStepSize()) {
            feasibleActions.add(new ActionImpl(state, actionPointer));
        }
        return feasibleActions;
    };

    Function<State, Action> idempotentAction = (Function<State, Action> & Serializable) s -> new ActionImpl(s,
            0.0);

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double inputCost = Math.pow(a.getAction(), 2) * R;
        double stateCost = Math.pow(fs.getInitialState(), 2) * Q;
        return inputCost + stateCost;
    };

    // Random Outcome Function

    RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> {
        double realizedNoise = ((StateImpl) finalState).getInitialState()
                - ((StateImpl) initialState).getInitialState() * Phi - ((ActionImpl) action).getAction() * G;
        return realizedNoise;
    };

    /*******************************************************************
     * Solve
     */

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 50;
    double reductionFactorPerStage = 1;

    // Value Function Processing Method: backward recursion
    double discountFactor = 1.0;
    int stateSpaceLowerBound = 10000000;
    float loadFactor = 0.8F;
    BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            stateSpaceLowerBound, loadFactor, HashType.THASHMAP);

    System.out.println("--------------Backward recursion--------------");
    StopWatch timer = new StopWatch();
    OperatingSystemMXBean osMBean;
    try {
        osMBean = ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
                ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
        long nanoBefore = System.nanoTime();
        long cpuBefore = osMBean.getProcessCpuTime();

        timer.start();
        recursion.runBackwardRecursionMonitoring();
        timer.stop();

        long cpuAfter = osMBean.getProcessCpuTime();
        long nanoAfter = System.nanoTime();

        long percent;
        if (nanoAfter > nanoBefore)
            percent = ((cpuAfter - cpuBefore) * 100L) / (nanoAfter - nanoBefore);
        else
            percent = 0;

        System.out.println(
                "Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println();
    double ETC = recursion.getExpectedCost(initialX);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialX);
    double action = recursion.getOptimalAction(initialState).getAction();
    System.out.println("Expected total cost (assuming an initial state " + initialX + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + timer);
    System.out.println();
}

From source file:ca.simplegames.micro.controllers.StatsController.java

public void execute(MicroContext context, Map configuration) throws ControllerException {
    Map<String, Object> systemInfo = new HashMap<String, Object>();
    Map<String, Object> osMap = new HashMap<String, Object>();
    MBeanServerConnection mbeanServer = ManagementFactory.getPlatformMBeanServer();

    OperatingSystemMXBean sunOperatingSystemMXBean = null;
    try {/*from www  .j  a va2 s  .  c om*/
        sunOperatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(mbeanServer,
                ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
    } catch (IOException e) {
        throw new ControllerException(e.getMessage());
    }

    Runtime rt = Runtime.getRuntime();
    long totalMemory = rt.totalMemory() / MEGA_BYTE;
    long freeMemory = rt.freeMemory() / MEGA_BYTE;
    long usedMemory = totalMemory - freeMemory;

    final long p100 = (int) Math.round(((double) freeMemory / (double) totalMemory) * 100);

    Map<String, Long> memInfo = new HashMap<String, Long>();

    memInfo.put("total", totalMemory);
    memInfo.put("used", usedMemory);
    memInfo.put("free", freeMemory);
    memInfo.put("percent_free", p100);

    systemInfo.put("memory", memInfo);
    systemInfo.put("powered_by", POWERED_BY_MICRO);

    //cpu usage in milli secs
    long currentCpuUsage = sunOperatingSystemMXBean.getProcessCpuTime() / 1000000;
    osMap.put("cpu_usage", currentCpuUsage);
    osMap.put("available_processors", sunOperatingSystemMXBean.getAvailableProcessors());
    osMap.put("system_load_average", sunOperatingSystemMXBean.getSystemLoadAverage());
    osMap.put("committed_virtual_memory_size", sunOperatingSystemMXBean.getCommittedVirtualMemorySize());
    osMap.put("free_physical_memory_size", sunOperatingSystemMXBean.getFreePhysicalMemorySize());
    osMap.put("total_physical_memory_size", sunOperatingSystemMXBean.getTotalPhysicalMemorySize());
    osMap.put("free_swap_space_size", sunOperatingSystemMXBean.getFreeSwapSpaceSize());
    osMap.put("total_swap_space_size", sunOperatingSystemMXBean.getTotalSwapSpaceSize());

    systemInfo.put("os", osMap);

    List<GarbageCollectorMXBean> gc = ManagementFactory.getGarbageCollectorMXBeans();
    List<Map> gcInfo = new ArrayList<Map>();

    for (GarbageCollectorMXBean aGc : gc) {
        Map<String, Object> gcMap = new HashMap<String, Object>();
        gcMap.put("name", aGc.getName());
        gcMap.put("collection_count", aGc.getCollectionCount());
        gcMap.put("collection_time", aGc.getCollectionTime());

        gcInfo.add(gcMap);
    }

    systemInfo.put("gc", gcInfo);

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    Map<String, Object> threadInfoMap = new HashMap<String, Object>(); // more to come ;)
    threadInfoMap.put("peak_thread_count", threadMXBean.getPeakThreadCount());
    threadInfoMap.put("thread_count", threadMXBean.getThreadCount());
    threadInfoMap.put("total_started_thread_count", threadMXBean.getTotalStartedThreadCount());

    long[] deadlockedThreads = threadMXBean.findMonitorDeadlockedThreads();
    threadInfoMap.put("dead_locked_thread_count", deadlockedThreads != null ? deadlockedThreads.length : 0);
    systemInfo.put("thread_info", threadInfoMap);

    JSONObject sysinfoJson = new JSONObject(Collections.singletonMap("system_info", systemInfo));

    String sysinfoString = null;
    try {
        sysinfoString = context.getRequest().getParameter("pretty") != null ? sysinfoJson.toString(2)
                : sysinfoJson.toString();
    } catch (JSONException e) {
        e.printStackTrace();
        throw new ControllerException(e.getMessage());
    }

    context.getRackResponse().withContentType(Mime.mimeType(JSON_TYPE)).withBody(sysinfoString)
            .withContentLength(sysinfoString.length()).with(Rack.MESSAGE_STATUS, HttpServletResponse.SC_OK);

    context.halt();
}

From source file:org.wso2.carbon.core.bootup.validator.SystemValidator.java

/**
 * @return RAM size (MB)//from   w  w w. j a v  a2 s . c  o m
 * @throws NullPointerException
 * @throws MalformedObjectNameException
 * @throws ReflectionException
 * @throws MBeanException
 * @throws InstanceNotFoundException
 * @throws AttributeNotFoundException
 */
private long getRAM() throws MalformedObjectNameException, AttributeNotFoundException,
        InstanceNotFoundException, MBeanException, ReflectionException {
    Long ramValue = null;
    ObjectName osBean = new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME);
    if (IBM_J9_VM.equals(System.getProperty("java.vm.name"))) {
        ramValue = (Long) mBeanServer.getAttribute(osBean, "TotalPhysicalMemory");
    } else { // if not IBM JVM we handling as if it is the Oracle JVM : Other JVMs are not supported
        ramValue = (Long) mBeanServer.getAttribute(osBean, "TotalPhysicalMemorySize");
    }
    return ramValue / MB_BASE;
}

From source file:org.wso2.carbon.core.bootup.validator.SystemValidator.java

/**
 * @return swap space (MB) in the system
 * @throws NullPointerException//from   w w  w . ja v  a2 s.  c o  m
 * @throws MalformedObjectNameException
 * @throws ReflectionException
 * @throws MBeanException
 * @throws InstanceNotFoundException
 * @throws AttributeNotFoundException
 */
private long getSwap() throws MalformedObjectNameException, AttributeNotFoundException,
        InstanceNotFoundException, MBeanException, ReflectionException {
    ObjectName osBean = new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME);
    Long swapValue = (Long) mBeanServer.getAttribute(osBean, "TotalSwapSpaceSize");
    return swapValue / MB_BASE;
}

From source file:org.wso2.carbon.core.bootup.validator.SystemValidator.java

/**
 * Unix OS Specific method to retrieve open files limit of the system
 *
 * @return open files limit of the system
 * @throws NullPointerException//from   w  ww.j a  va2s.com
 * @throws MalformedObjectNameException
 * @throws ReflectionException
 * @throws MBeanException
 * @throws InstanceNotFoundException
 * @throws AttributeNotFoundException
 */
private long getOpenFilesLimit() throws Exception {
    ObjectName osBean = new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME);
    long maxFDValue = 0;
    if (IBM_J9_VM.equals(System.getProperty("java.vm.name"))) {
        BufferedReader output = null;
        try {
            Process p = Runtime.getRuntime().exec(new String[] { "bash", "-c", "ulimit -n" });
            InputStream in = p.getInputStream();
            output = new BufferedReader(new InputStreamReader(in));
            String maxFileDesCount;
            if ((maxFileDesCount = output.readLine()) != null) {
                maxFDValue = Long.parseLong(maxFileDesCount);
            }
        } catch (IOException exception) {
            log.warn("Could not get the maximum file descriptor count ", exception);
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    log.error("Error closing buffer reader ", e);
                }
            }
        }
    } else {
        maxFDValue = (Long) mBeanServer.getAttribute(osBean, "MaxFileDescriptorCount");
    }
    return maxFDValue;
}

From source file:org.talend.designer.runtime.visualization.views.RuntimeGraphcsComposite.java

private void loadOverviewChartSet(IActiveJvm activeJvm) throws JvmCoreException {
    final int[] blue = new int[] { 0, 255, 255 };
    final int[] red = new int[] { 255, 0, 0 };
    final int[] green = new int[] { 0, 255, 0 };
    final int[] lightgeen = new int[] { 128, 255, 0 };

    final int[] darkRed = new int[] { 255, 0, 128 };

    final int[] orange = new int[] { 255, 255, 0 };
    IMBeanServer server = activeJvm.getMBeanServer();
    server.getMonitoredAttributeGroups().clear();

    IMonitoredMXBeanGroup group = server.addMonitoredAttributeGroup(MonitorAttributeName.HEAP_MEMORY,
            AxisUnit.MBytes);//from w w  w  .  jav  a 2  s .  c  o m

    group.addAttribute(ManagementFactory.MEMORY_MXBEAN_NAME, MonitorAttributeName.HEAP_MEMORY_USE, green);

    group.addAttribute(ManagementFactory.MEMORY_MXBEAN_NAME, MonitorAttributeName.HEAP_MEMORY_SIZE, darkRed);

    group.addAttribute(ManagementFactory.MEMORY_MXBEAN_NAME, MonitorAttributeName.HEAP_MEMORY_NINTY, blue);

    group.addAttribute(ManagementFactory.MEMORY_MXBEAN_NAME, MonitorAttributeName.HEAP_MEMORY_THREE_QUARTER,
            orange);

    group = server.addMonitoredAttributeGroup(MonitorAttributeName.CPU_USE, AxisUnit.Percent);
    group.addAttribute(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, MonitorAttributeName.CPU_TIME,
            lightgeen);
}

From source file:org.kuali.test.runner.execution.TestExecutionContext.java

private void writePerformanceData(TestOperation op, long operationElaspedTime) {
    if (isPerformanceDataRequired()) {

        if (performanceData == null) {
            performanceData = new ArrayList<String[]>();
        }/* w w  w.j  a  va2 s  . c  om*/

        String submitElementName = getLastHttpSubmitElementName();
        ;

        if (op.getOperationType().equals(TestOperationType.HTTP_REQUEST)) {
            String[] rec = getInitializedPerformanceDataRecord();
            rec[8] = Constants.PERFORMANCE_ATTRIBUTE_TYPE_CLIENT;
            rec[9] = Constants.CLIENT_PERFORMANCE_ATTRIBUTE_HTTP_RESPONSE_TIME;
            rec[10] = Constants.PRIMITIVE_LONG_TYPE;
            rec[11] = "" + operationElaspedTime;
            rec[12] = submitElementName;
            rec[13] = (op.getOperation().getHtmlRequestOperation().getMethod() + ": "
                    + op.getOperation().getHtmlRequestOperation().getUrl());
            performanceData.add(rec);
        }

        JmxConnection jmxconn = Utils.findJmxConnection(configuration, platform.getJmxConnectionName());

        if ((jmxconn != null) && (jmxconn.getPerformanceMonitoringAttributes() != null)) {
            JMXConnector conn = null;
            try {
                conn = Utils.getJMXConnector(configuration, jmxconn);
                if (conn != null) {
                    MBeanServerConnection mbeanconn = conn.getMBeanServerConnection();
                    for (PerformanceMonitoringAttribute att : jmxconn.getPerformanceMonitoringAttributes()
                            .getPerformanceMonitoringAttributeArray()) {

                        Object value = "";
                        if (ManagementFactory.MEMORY_MXBEAN_NAME.equals(att.getType())) {
                            MemoryMXBean mbean = ManagementFactory.newPlatformMXBeanProxy(mbeanconn,
                                    ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
                            value = getValueFromMXBeanObject(att.getName(), mbean);
                        } else if (ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME.equals(att.getType())) {
                            OperatingSystemMXBean mbean = ManagementFactory.newPlatformMXBeanProxy(mbeanconn,
                                    att.getType(), OperatingSystemMXBean.class);
                            value = getValueFromMXBeanObject(att.getName(), mbean);
                        } else if (ManagementFactory.THREAD_MXBEAN_NAME.equals(att.getType())) {
                            ThreadMXBean mbean = ManagementFactory.newPlatformMXBeanProxy(mbeanconn,
                                    att.getType(), ThreadMXBean.class);
                            value = getValueFromMXBeanObject(att.getName(), mbean);
                        }

                        if ((value != null) && StringUtils.isNotBlank(value.toString())) {
                            String[] rec = getInitializedPerformanceDataRecord();

                            int pos = att.getType().indexOf(Constants.SEPARATOR_EQUALS);

                            if (pos > -1) {
                                rec[8] = att.getType().substring(pos + 1);
                            } else {
                                rec[8] = att.getType();
                            }
                            rec[9] = att.getName();
                            rec[10] = att.getType();
                            rec[11] = value.toString();
                            rec[12] = submitElementName;
                            rec[13] = att.getDescription();

                            performanceData.add(rec);
                        }
                    }
                }
            }

            catch (Exception ex) {
                LOG.error(ex.toString(), ex);
            }

            finally {
                if (conn != null) {
                    try {
                        conn.close();
                    }

                    catch (Exception ex) {
                    }
                    ;
                }
            }
        }
    }
}