Example usage for java.lang Runtime availableProcessors

List of usage examples for java.lang Runtime availableProcessors

Introduction

In this page you can find the example usage for java.lang Runtime availableProcessors.

Prototype

public native int availableProcessors();

Source Link

Document

Returns the number of processors available to the Java virtual machine.

Usage

From source file:com.l2jfree.gameserver.util.Util.java

public static int getAvailableProcessors() {
    Runtime rt = Runtime.getRuntime();
    return rt.availableProcessors();
}

From source file:mobisocial.musubi.ui.fragments.FeedViewFragment.java

private static int getBestBatchSize() {
    Runtime runtime = Runtime.getRuntime();
    if (runtime.availableProcessors() > 1)
        return 100;

    FileInputStream in = null;/*from w ww  .ja va 2 s.  co  m*/
    try {
        File max_cpu_freq = new File("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq");
        in = new FileInputStream(max_cpu_freq);
        byte[] freq_bytes = IOUtils.toByteArray(in);
        String freq_string = new String(freq_bytes);
        double freq = Double.valueOf(freq_string);
        if (freq > 950000) {
            return 50;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
            Log.e(FeedViewFragment.TAG, "failed to close frequency counter file", e);
        }
    }
    return 15;
}

From source file:com.nridge.core.base.std.Platform.java

/**
 * Create a log message containing JVM Heap Memory statistics.
 * <p>totalMemory(): Returns the total amount of memory in the
 * Java virtual machine. The value returned by this method may
 * vary over time, depending on the host environment. Note that
 * the amount of memory required to hold an object of any given
 * type may be implementation-dependent.</p>
 * <p>maxMemory(): Returns the maximum amount of memory that the
 * Java virtual machine will attempt to use. If there is no inherent
 * limit then the value Long.MAX_VALUE will be returned.</p>
 * <p>freeMemory(): Returns the amount of free memory in the Java
 * Virtual Machine. Calling the gc method may result in increasing
 * the value returned by freeMemory.</p>
 * <p>In reference to your question, maxMemory() returns the -Xmx value.
 * You may be wondering why there is a totalMemory() AND a maxMemory().
 * The answer is that the JVM allocates memory lazily.</p>
 *
 * @param aTitle Title to save with log entry.
 *
 * @return Log message./*  w  ww.  j  a  v  a  2 s .c o  m*/
 *
 * @see <a href="http://stackoverflow.com/questions/3571203/what-is-the-exact-meaning-of-runtime-getruntime-totalmemory-and-freememory">Runtime Memory</a>
 * @see <a href="http://www.mkyong.com/java/find-out-your-java-heap-memory-size/">Heap Memory</a>
 * @see <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html">JavaDoc Runtime</a>
 */
public static String jvmLogMessage(String aTitle) {
    Runtime jvmRuntime = Runtime.getRuntime();

    if (StringUtils.isEmpty(aTitle))
        aTitle = "JVM";

    long maxMemory = jvmRuntime.maxMemory();
    long freeMemory = jvmRuntime.freeMemory();
    long totalMemory = jvmRuntime.totalMemory();
    long usedMemory = totalMemory - freeMemory;
    long availMemory = maxMemory - usedMemory;

    String logMsg = String.format("%s: Processors: %d, Mem Max: %s, Mem Total: %s, Mem Used: %s, Mem Avail: %s",
            aTitle, jvmRuntime.availableProcessors(), bytesToString(maxMemory), bytesToString(totalMemory),
            bytesToString(usedMemory), bytesToString(availMemory));
    return logMsg;
}

From source file:co.aikar.timings.TimingsExport.java

/**
 * Checks if any pending reports are being requested, and builds one if needed.
 *///from   w w w.j  ava2s.c  o m
static void reportTimings() {
    if (requestingReport.isEmpty()) {
        return;
    }
    TimingsReportListener listeners = new TimingsReportListener(requestingReport);
    listeners.addConsoleIfNeeded();

    requestingReport.clear();
    long now = System.currentTimeMillis();
    final long lastReportDiff = now - lastReport;
    if (lastReportDiff < 60000) {
        listeners.sendMessage(ChatColor.RED + "Please wait at least 1 minute in between Timings reports. ("
                + (int) ((60000 - lastReportDiff) / 1000) + " seconds)");
        listeners.done();
        return;
    }
    final long lastStartDiff = now - TimingsManager.timingStart;
    if (lastStartDiff < 180000) {
        listeners.sendMessage(ChatColor.RED
                + "Please wait at least 3 minutes before generating a Timings report. Unlike Timings v1, v2 benefits from longer timings and is not as useful with short timings. ("
                + (int) ((180000 - lastStartDiff) / 1000) + " seconds)");
        listeners.done();
        return;
    }
    listeners.sendMessage(ChatColor.GREEN + "Preparing Timings Report...");
    lastReport = now;
    Map parent = createObject(
            // Get some basic system details about the server
            pair("version", Bukkit.getVersion()), pair("maxplayers", Bukkit.getMaxPlayers()),
            pair("start", TimingsManager.timingStart / 1000), pair("end", System.currentTimeMillis() / 1000),
            pair("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000));
    if (!TimingsManager.privacy) {
        appendObjectData(parent, pair("server", Bukkit.getServerName()),
                pair("motd", Bukkit.getServer().getMotd()),
                pair("online-mode", Bukkit.getServer().getOnlineMode()),
                pair("icon", Bukkit.getServer().getServerIcon().getData()));
    }

    final Runtime runtime = Runtime.getRuntime();
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();

    parent.put("system", createObject(pair("timingcost", getCost()),
            pair("name", System.getProperty("os.name")), pair("version", System.getProperty("os.version")),
            pair("jvmversion", System.getProperty("java.version")), pair("arch", System.getProperty("os.arch")),
            pair("maxmem", runtime.maxMemory()), pair("cpu", runtime.availableProcessors()),
            pair("runtime", ManagementFactory.getRuntimeMXBean().getUptime()),
            pair("flags", StringUtils.join(runtimeBean.getInputArguments(), " ")),
            pair("gc",
                    toObjectMapper(ManagementFactory.getGarbageCollectorMXBeans(),
                            input -> pair(input.getName(),
                                    toArray(input.getCollectionCount(), input.getCollectionTime()))))));

    Set<Material> tileEntityTypeSet = Sets.newHashSet();
    Set<EntityType> entityTypeSet = Sets.newHashSet();

    int size = HISTORY.size();
    TimingHistory[] history = new TimingHistory[size + 1];
    int i = 0;
    for (TimingHistory timingHistory : HISTORY) {
        tileEntityTypeSet.addAll(timingHistory.tileEntityTypeSet);
        entityTypeSet.addAll(timingHistory.entityTypeSet);
        history[i++] = timingHistory;
    }

    history[i] = new TimingHistory(); // Current snapshot
    tileEntityTypeSet.addAll(history[i].tileEntityTypeSet);
    entityTypeSet.addAll(history[i].entityTypeSet);

    Map handlers = createObject();
    for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
        for (TimingHandler id : group.handlers) {
            if (!id.isTimed() && !id.isSpecial()) {
                continue;
            }
            handlers.put(id.id, toArray(group.id, id.name));
        }
    }

    parent.put("idmap",
            createObject(
                    pair("groups",
                            toObjectMapper(
                                    TimingIdentifier.GROUP_MAP.values(), group -> pair(group.id, group.name))),
                    pair("handlers", handlers), pair(
                            "worlds",
                            toObjectMapper(TimingHistory.worldMap.entrySet(),
                                    input -> pair(input.getValue(), input.getKey()))),
                    pair("tileentity",
                            toObjectMapper(tileEntityTypeSet, input -> pair(input.getId(), input.name()))),
                    pair("entity",
                            toObjectMapper(entityTypeSet, input -> pair(input.getTypeId(), input.name())))));

    // Information about loaded plugins

    parent.put("plugins",
            toObjectMapper(Bukkit.getPluginManager().getPlugins(), plugin -> pair(plugin.getName(),
                    createObject(pair("version", plugin.getDescription().getVersion()),
                            pair("description",
                                    String.valueOf(plugin.getDescription().getDescription()).trim()),
                            pair("website", plugin.getDescription().getWebsite()),
                            pair("authors", StringUtils.join(plugin.getDescription().getAuthors(), ", "))))));

    // Information on the users Config

    parent.put("config", createObject(pair("bukkit", mapAsJSON(Bukkit.spigot().getConfig(), null))));

    new TimingsExport(listeners, parent, history).start();
}

From source file:org.spigotmc.timings.TimingsExport.java

/**
 * Builds an XML report of the timings to be uploaded for parsing.
 *
 * @param sender Who to report to//www.  j  ava 2  s  .  c  o  m
 */
static void reportTimings(CommandSender sender) {
    Map parent = createObject(
            // Get some basic system details about the server
            pair("version", Bukkit.getVersion()), pair("maxplayers", Bukkit.getMaxPlayers()),
            pair("start", TimingsManager.timingStart / 1000), pair("end", System.currentTimeMillis() / 1000),
            pair("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000));
    if (!TimingsManager.privacy) {
        appendObjectData(parent, pair("server", Bukkit.getServerName()),
                pair("motd", Bukkit.getServer().getMotd()),
                pair("online-mode", Bukkit.getServer().getOnlineMode()),
                pair("icon", Bukkit.getServer().getServerIcon().getData()));
    }

    final Runtime runtime = Runtime.getRuntime();

    parent.put("system",
            createObject(pair("timingcost", getCost()), pair("name", System.getProperty("os.name")),
                    pair("version", System.getProperty("os.version")),
                    pair("arch", System.getProperty("os.arch")), pair("totalmem", runtime.totalMemory()),
                    pair("usedmem", runtime.totalMemory() - runtime.freeMemory()),
                    pair("maxmem", runtime.maxMemory()), pair("cpu", runtime.availableProcessors()),
                    pair("runtime", (System.currentTimeMillis() / 1000) - TimingsManager.SERVER_START)));

    Set<Material> tileEntityTypeSet = Sets.newHashSet();
    Set<EntityType> entityTypeSet = Sets.newHashSet();

    int size = HISTORY.size();
    TimingHistory[] history = new TimingHistory[size + 1];
    int i = 0;
    for (TimingHistory timingHistory : HISTORY) {
        tileEntityTypeSet.addAll(timingHistory.tileEntityTypeSet);
        entityTypeSet.addAll(timingHistory.entityTypeSet);
        history[i++] = timingHistory;
    }

    history[i] = new TimingHistory(); // Current snapshot
    tileEntityTypeSet.addAll(history[i].tileEntityTypeSet);
    entityTypeSet.addAll(history[i].entityTypeSet);

    Map handlers = createObject();
    for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
        for (TimingHandler id : group.handlers) {
            if (!id.timed && !id.isSpecial()) {
                continue;
            }
            handlers.put(id.id, toArray(group.id, id.name));
        }
    }

    parent.put("idmap", createObject(pair("groups", toObjectMapper(TimingIdentifier.GROUP_MAP.values(),
            new Function<TimingIdentifier.TimingGroup, JSONPair>() {
                @Override
                public JSONPair apply(TimingIdentifier.TimingGroup group) {
                    return pair(group.id, group.name);
                }
            })), pair("handlers", handlers), pair("worlds", toObjectMapper(TimingHistory.worldMap.entrySet(),
                    new Function<Map.Entry<String, Integer>, JSONPair>() {
                        @Override
                        public JSONPair apply(Map.Entry<String, Integer> input) {
                            return pair(input.getValue(), input.getKey());
                        }
                    })),
            pair("tileentity", toObjectMapper(tileEntityTypeSet, new Function<Material, JSONPair>() {
                @Override
                public JSONPair apply(Material input) {
                    return pair(input.getId(), input.name());
                }
            })), pair("entity", toObjectMapper(entityTypeSet, new Function<EntityType, JSONPair>() {
                @Override
                public JSONPair apply(EntityType input) {
                    return pair(input.getTypeId(), input.name());
                }
            }))));

    // Information about loaded plugins

    parent.put("plugins",
            toObjectMapper(Bukkit.getPluginManager().getPlugins(), new Function<Plugin, JSONPair>() {
                @Override
                public JSONPair apply(Plugin plugin) {
                    return pair(plugin.getName(), createObject(
                            pair("version", plugin.getDescription().getVersion()),
                            pair("description",
                                    String.valueOf(plugin.getDescription().getDescription()).trim()),
                            pair("website", plugin.getDescription().getWebsite()),
                            pair("authors", StringUtils.join(plugin.getDescription().getAuthors(), ", "))));
                }
            }));

    // Information on the users Config

    parent.put("config", createObject(pair("spigot", mapAsJSON(Bukkit.spigot().getSpigotConfig(), null)),
            pair("bukkit", mapAsJSON(Bukkit.spigot().getBukkitConfig(), null))));

    new TimingsExport(sender, parent, history).start();
}

From source file:ezid.EZIDClient.java

private void startExecutorLoop() {
    // Query the runtime to see how many CPUs are available, and configure that many threads
    Runtime runtime = Runtime.getRuntime();
    int numCores = runtime.availableProcessors();
    log.info("Number of cores available: " + numCores);
    executor = Executors.newFixedThreadPool(numCores);
}

From source file:edu.ucsb.nceas.ezid.EZIDClient.java

private void startExecutorLoop() {
    // Query the runtime to see how many CPUs are available, and configure that many threads
    Runtime runtime = Runtime.getRuntime();
    int numCores = runtime.availableProcessors();
    log.debug("Number of cores available: " + numCores);
    executor = Executors.newFixedThreadPool(numCores);
}

From source file:org.emergya.backtrackTSP.BackTrackingTSP.java

/**
 * Initialices the distance matrix on background while tsp is running.
 * //from  w w  w .java  2 s  .  c om
 * @param distances
 * @param bag
 */
private void initializeMatrix(DistanceMatrix distances, TSPStopBag bag) {

    Runtime runtime = Runtime.getRuntime();
    int numthreads = runtime.availableProcessors() * 3;

    executor2 = Executors.newFixedThreadPool(numthreads);

    List<BacktrackStop> candidates = null;
    candidates = new ArrayList<BacktrackStop>();
    for (TSPStop stop : bag.getAll())
        candidates.add((BacktrackStop) stop);

    for (BacktrackStop from : candidates) {
        executor2.execute(new InitializeDistances(from, candidates, distances));
    }
    executor2.shutdown();
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                executor2.awaitTermination(6, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                LOG.error(e, e);
            }
        }
    };
    t.start();
}

From source file:org.emergya.backtrackTSP.BackTrackingTSP.java

public List<TSPStop> order(TSPStopBag _bag) {
    long time = System.currentTimeMillis();

    Runtime runtime = Runtime.getRuntime();
    int numthreads = runtime.availableProcessors() * 10;

    executor = Executors.newFixedThreadPool(numthreads);

    DistanceMatrix distances = new DistanceMatrix();

    initializeMatrix(distances, _bag);/*from  w  ww  . j  av  a2s .c  om*/

    SolutionContainer solutions = new SolutionContainer(distances);

    if (_bag.size() > 7) {
        if (_bag.hasLast()) {
            // run(executor, new AStar(_bag, distances, solutions));
            run(executor, new HeuristicBacktracking(_bag, distances, solutions));
        } else {
            for (TSPStop stop : _bag.getAll()) {
                List<TSPStop> stops = new ArrayList<TSPStop>();
                stops.addAll(_bag.getAll());
                stops.remove(stop);

                BacktrackStopBag bag = new BacktrackStopBag(stops, _bag.getFirst(), stop);
                // run(executor, new AStar(bag, distances, solutions));
                run(executor, new HeuristicBacktracking(bag, distances, solutions));
            }
        }
    }
    run(executor, new Backtracking(_bag, distances, solutions));

    executor.shutdown();

    try {
        if (!executor.awaitTermination(this.seconds - (System.currentTimeMillis() - time) / 1000,
                TimeUnit.SECONDS)) {
            stop();
        }
    } catch (InterruptedException e) {
        if (!this.partialSolution) {
            throw new RuntimeException("Timeout reached. I couldn't find a solution on a proper time. "
                    + "Please, give me another chance with more time or"
                    + " accept a partial solution. I won't fail you, I promise.", e);
        }
    }

    return getBest(solutions, distances, _bag.size());
}

From source file:org.loklak.api.susi.StatusService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization rights,
        JSONObjectWithDefault permissions) throws APIException {

    post.setResponse(response, "application/javascript");

    // generate json
    Runtime runtime = Runtime.getRuntime();
    JSONObject json = new JSONObject(true);
    JSONObject system = new JSONObject(true);
    system.put("assigned_memory", runtime.maxMemory());
    system.put("used_memory", runtime.totalMemory() - runtime.freeMemory());
    system.put("available_memory", runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory());
    system.put("cores", runtime.availableProcessors());
    system.put("threads", Thread.activeCount());
    system.put("runtime", System.currentTimeMillis() - Caretaker.startupTime);
    system.put("load_system_average", OS.getSystemLoadAverage());
    system.put("load_system_cpu", OS.getSystemCpuLoad());
    system.put("load_process_cpu", OS.getProcessCpuLoad());
    system.put("server_threads", SusiServer.getServerThreads());
    system.put("server_uri", SusiServer.getServerURI());

    JSONObject index = new JSONObject(true);
    JSONObject messages = new JSONObject(true);
    JSONObject queue = new JSONObject(true);
    messages.put("queue", queue);
    JSONObject users = new JSONObject(true);
    JSONObject queries = new JSONObject(true);
    JSONObject accounts = new JSONObject(true);
    JSONObject user = new JSONObject(true);
    index.put("messages", messages);
    index.put("users", users);
    index.put("queries", queries);
    index.put("accounts", accounts);
    index.put("user", user);

    JSONObject client_info = new JSONObject(true);
    client_info.put("RemoteHost", post.getClientHost());
    client_info.put("IsLocalhost", post.isLocalhostAccess() ? "true" : "false");

    JSONObject request_header = new JSONObject(true);
    Enumeration<String> he = post.getRequest().getHeaderNames();
    while (he.hasMoreElements()) {
        String h = he.nextElement();
        request_header.put(h, post.getRequest().getHeader(h));
    }/*from  ww  w. j a va 2s  . co m*/
    client_info.put("request_header", request_header);

    json.put("system", system);
    json.put("index", index);
    json.put("client_info", client_info);

    return json;
}