Example usage for java.lang Runtime freeMemory

List of usage examples for java.lang Runtime freeMemory

Introduction

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

Prototype

public native long freeMemory();

Source Link

Document

Returns the amount of free memory in the Java Virtual Machine.

Usage

From source file:org.sakaiproject.util.BaseDbBinarySingleStorage.java

/**
 * @param entry/* w  w w  . j  av  a  2s. c  om*/
 * @return
 */
private Object getBlob(Entity entry) {
    Runtime r = Runtime.getRuntime();
    long ms = r.freeMemory();
    long start = System.currentTimeMillis();
    try {
        EntityReader er_user = (EntityReader) m_user;
        try {

            EntityReaderHandler erHandler = er_user.getHandler();
            return erHandler.serialize(entry);

        } catch (EntityParseException ep) {
            M_log.warn("Unable to Serialize Entity, falling back to XML " + entry.getId(), ep);
        }
        return null;
    } finally {
        long t = System.currentTimeMillis() - start;
        long me = r.freeMemory();
        long md = ms - me;
        if (md >= 0) {
            mtotal += md;
        } else {
            if (ntime != 0) {
                mtotal += (mtotal / ntime);
            }
        }
        ttotal += t;
        ntime++;
        if (ntime % 100 == 0) {
            double a = (1.0 * ttotal) / (1.0 * ntime);
            double m = (1.0 * mtotal) / (1.0 * ntime);
            M_log.debug("Average Serialization now " + (a) + "ms " + m + " bytes");
        }

    }
}

From source file:org.sakaiproject.util.BaseDbDualSingleStorage.java

/**
 * Read one Resource from xml/* ww w  .ja  va  2s .  c o  m*/
 * 
 * @param xml
 *        An string containing the xml which describes the resource.
 * @return The Resource object created from the xml.
 */
protected Entity readResource(String xml, byte[] blob) {
    Runtime r = Runtime.getRuntime();
    long ms = r.freeMemory();
    long start = System.currentTimeMillis();
    String type = "";
    try {
        type = "direct";
        EntityReader de_user = (EntityReader) m_user;
        EntityReaderHandler de_handler = de_user.getHandler();
        return de_handler.parse(null, xml, blob);
    } catch (Exception e) {
        M_log.warn("readResource(): " + e.getMessage());
        M_log.warn("readResource(): ", e);
        return null;
    } finally {
        long t = System.currentTimeMillis() - start;
        long me = r.freeMemory();
        long md = ms - me;
        if (md >= 0) {
            rmtotal += md;
        } else {
            if (rntime != 0) {
                rmtotal += (rmtotal / rntime);
            }
        }
        rttotal += t;
        rntime++;
        if (rntime % 100 == 0) {
            double a = (1.0 * rttotal) / (1.0 * rntime);
            double m = (1.0 * rmtotal) / (1.0 * rntime);
            M_log.debug("Average " + type + " Parse now " + (a) + "ms " + m + " bytes");
        }

    }
}

From source file:org.schedulesdirect.grabber.Grabber.java

private void updateZip(NetworkEpgClient clnt) throws IOException, JSONException, JsonParseException {
    Set<String> completedListings = new HashSet<String>();
    LOG.debug(String.format("Using %d worker threads", globalOpts.getMaxThreads()));
    pool = createThreadPoolExecutor();/* w  w  w  . ja  v a 2  s .c  o  m*/
    start = System.currentTimeMillis();
    File dest = grabOpts.getTarget();
    cachedSeriesIds = new HashSet<String>();
    boolean rmDest = false;
    if (dest.exists()) {
        ZipEpgClient zipClnt = null;
        try {
            zipClnt = new ZipEpgClient(dest);
            if (!zipClnt.getUserStatus().getLastServerRefresh()
                    .before(clnt.getUserStatus().getLastServerRefresh())) {
                LOG.info(
                        "Current cache file contains latest data from Schedules Direct server; use --force-download to force a new download from server.");
                boolean force = grabOpts.isForce();
                if (!force)
                    return;
                else
                    LOG.warn("Forcing an update of data with the server due to user request!");
            }
        } catch (Exception e) {
            if (grabOpts.isKeep()) {
                LOG.error("Existing cache is invalid, keeping by user request!", e);
                return;
            } else {
                LOG.warn("Existing cache is invalid, deleting it; use --keep-bad-cache to keep existing cache!",
                        e);
                rmDest = true;
            }
        } finally {
            if (zipClnt != null)
                try {
                    zipClnt.close();
                } catch (IOException e) {
                }
            if (rmDest && !dest.delete())
                throw new IOException("Unable to delete " + dest);
        }
    }

    freshZip = !dest.exists();
    try (FileSystem vfs = FileSystems.newFileSystem(new URI(String.format("jar:%s", dest.toURI())),
            Collections.singletonMap("create", "true"))) {
        if (freshZip) {
            Path target = vfs.getPath(ZipEpgClient.ZIP_VER_FILE);
            Files.write(target, Integer.toString(ZipEpgClient.ZIP_VER).getBytes(ZipEpgClient.ZIP_CHARSET));
        }
        ProgramCache progCache = ProgramCache.get(vfs);
        Path lineups = vfs.getPath("lineups.txt");
        Files.deleteIfExists(lineups);
        Path scheds = vfs.getPath("/schedules/");
        if (!Files.isDirectory(scheds))
            Files.createDirectory(scheds);
        Path maps = vfs.getPath("/maps/");
        PathUtils.removeDirectory(maps);
        Files.createDirectory(maps);
        Path progs = vfs.getPath("/programs/");
        if (!Files.isDirectory(progs))
            Files.createDirectory(progs);
        Path logos = vfs.getPath("/logos/");
        if (!Files.isDirectory(logos))
            Files.createDirectory(logos);
        Path md5s = vfs.getPath("/md5s/");
        if (!Files.isDirectory(md5s))
            Files.createDirectory(md5s);
        Path cache = vfs.getPath(LOGO_CACHE);
        if (Files.exists(cache)) {
            String cacheData = new String(Files.readAllBytes(cache), ZipEpgClient.ZIP_CHARSET);
            logoCache = Config.get().getObjectMapper().readValue(cacheData, JSONObject.class);
        } else
            logoCache = new JSONObject();
        Path seriesInfo = vfs.getPath("/seriesInfo/");
        if (!Files.isDirectory(seriesInfo))
            Files.createDirectories(seriesInfo);
        loadSeriesInfoIds(seriesInfo);
        missingSeriesIds = Collections.synchronizedSet(new HashSet<String>());
        loadRetryIds(vfs.getPath(SERIES_INFO_DATA));

        JSONObject resp = Config.get().getObjectMapper().readValue(
                factory.get(DefaultJsonRequest.Action.GET, RestNouns.LINEUPS, clnt.getHash(),
                        clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null),
                JSONObject.class);
        if (!JsonResponseUtils.isErrorResponse(resp))
            Files.write(lineups, resp.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET));
        else
            LOG.error("Received error response when requesting lineup data!");

        for (Lineup l : clnt.getLineups()) {
            buildStationList();
            JSONObject o = Config.get().getObjectMapper()
                    .readValue(
                            factory.get(DefaultJsonRequest.Action.GET, l.getUri(), clnt.getHash(),
                                    clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null),
                            JSONObject.class);
            Files.write(vfs.getPath("/maps", ZipEpgClient.scrubFileName(String.format("%s.txt", l.getId()))),
                    o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET));
            JSONArray stations = o.getJSONArray("stations");
            JSONArray ids = new JSONArray();
            for (int i = 0; i < stations.length(); ++i) {
                JSONObject obj = stations.getJSONObject(i);
                String sid = obj.getString("stationID");
                if (stationList != null && !stationList.contains(sid))
                    LOG.debug(String.format("Skipped %s; not listed in station file", sid));
                else if (completedListings.add(sid)) {
                    ids.put(sid);
                    if (!grabOpts.isNoLogos()) {
                        if (logoCacheInvalid(obj))
                            pool.execute(new LogoTask(obj, vfs, logoCache));
                        else if (LOG.isDebugEnabled())
                            LOG.debug(String.format("Skipped logo for %s; already cached!",
                                    obj.optString("callsign", null)));
                    } else if (!logosWarned) {
                        logosWarned = true;
                        LOG.warn("Logo downloads disabled by user request!");
                    }
                } else
                    LOG.debug(String.format("Skipped %s; already downloaded.", sid));
                //pool.setMaximumPoolSize(5); // Processing these new schedules takes all kinds of memory!
                if (ids.length() == grabOpts.getMaxSchedChunk()) {
                    pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory));
                    ids = new JSONArray();
                }
            }
            if (ids.length() > 0)
                pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory));
        }
        pool.shutdown();
        try {
            LOG.debug("Waiting for SchedLogoExecutor to terminate...");
            if (pool.awaitTermination(15, TimeUnit.MINUTES))
                LOG.debug("SchedLogoExecutor: Terminated successfully.");
            else {
                failedTask = true;
                LOG.warn(
                        "SchedLogoExecutor: Termination timed out; some tasks probably didn't finish properly!");
            }
        } catch (InterruptedException e) {
            failedTask = true;
            LOG.warn(
                    "SchedLogoExecutor: Termination interrupted); some tasks probably didn't finish properly!");
        }
        Files.write(cache, logoCache.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET),
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        ScheduleTask.commit(vfs);

        pool = createThreadPoolExecutor();
        //pool.setMaximumPoolSize(5); // Again, we've got memory problems
        String[] dirtyPrograms = progCache.getDirtyIds();
        progCache.markAllClean();
        progCache = null;
        LOG.info(String.format("Identified %d program ids requiring an update!", dirtyPrograms.length));
        Collection<String> progIds = new ArrayList<String>();
        for (String progId : dirtyPrograms) {
            progIds.add(progId);
            if (progIds.size() == grabOpts.getMaxProgChunk()) {
                pool.execute(new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null,
                        false));
                progIds.clear();
            }
        }
        if (progIds.size() > 0)
            pool.execute(
                    new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null, false));
        pool.shutdown();
        try {
            LOG.debug("Waiting for ProgramExecutor to terminate...");
            if (pool.awaitTermination(15, TimeUnit.MINUTES)) {
                LOG.debug("ProgramExecutor: Terminated successfully.");
                Iterator<String> itr = missingSeriesIds.iterator();
                while (itr.hasNext()) {
                    String id = itr.next();
                    if (cachedSeriesIds.contains(id))
                        itr.remove();
                }
                if (missingSeriesIds.size() > 0) {
                    LOG.info(String.format("Grabbing %d series info programs!", missingSeriesIds.size()));
                    Set<String> retrySet = new HashSet<>();
                    try {
                        new ProgramTask(missingSeriesIds, vfs, clnt, factory, missingSeriesIds, "seriesInfo",
                                retrySet, true).run();
                    } catch (RuntimeException e) {
                        LOG.error("SeriesInfo task failed!", e);
                        Grabber.failedTask = true;
                    }
                    Path seriesInfoData = vfs.getPath(SERIES_INFO_DATA);
                    if (retrySet.size() > 0) {
                        StringBuilder sb = new StringBuilder();
                        for (String id : retrySet)
                            sb.append(id + "\n");
                        Files.write(seriesInfoData, sb.toString().getBytes(ZipEpgClient.ZIP_CHARSET),
                                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING,
                                StandardOpenOption.CREATE);
                    } else if (Files.exists(seriesInfoData))
                        Files.delete(seriesInfoData);
                }
            } else {
                failedTask = true;
                LOG.warn("ProgramExecutor: Termination timed out; some tasks probably didn't finish properly!");
            }
        } catch (InterruptedException e) {
            failedTask = true;
            LOG.warn("ProgramExecutor: Termination interrupted); some tasks probably didn't finish properly!");
        }

        String userData = clnt.getUserStatus().toJson();
        if (failedTask) {
            LOG.error("One or more tasks failed!  Resetting last data refresh timestamp to zero.");
            SimpleDateFormat fmt = Config.get().getDateTimeFormat();
            String exp = fmt.format(new Date(0L));
            JSONObject o = Config.get().getObjectMapper().readValue(userData, JSONObject.class);
            o.put("lastDataUpdate", exp);
            userData = o.toString(2);
        }
        Path p = vfs.getPath(USER_DATA);
        Files.write(p, userData.getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
        removeIgnoredStations(vfs);
    } catch (URISyntaxException e1) {
        throw new RuntimeException(e1);
    } finally {
        Runtime rt = Runtime.getRuntime();
        LOG.info(String.format("MemStats:%n\tFREE: %s%n\tUSED: %s%n\t MAX: %s",
                FileUtils.byteCountToDisplaySize(rt.freeMemory()),
                FileUtils.byteCountToDisplaySize(rt.totalMemory()),
                FileUtils.byteCountToDisplaySize(rt.maxMemory())));
    }
}

From source file:pl.edu.icm.visnow.system.main.VisNow.java

public long getMemoryAvailable() {
    Runtime r = Runtime.getRuntime();
    r.gc();//  w w  w .jav a2 s. c  o  m
    long total = r.totalMemory();
    long free = r.freeMemory();
    long used = total - free;
    return (memoryMax - used);
}

From source file:de.evaluationtool.gui.EvaluationFrame.java

public void updateTitle() {
    int mb = 1024 * 1024;
    Runtime runtime = Runtime.getRuntime();

    int used = (int) ((runtime.totalMemory() - runtime.freeMemory()) / mb);
    int max = (int) ((runtime.maxMemory() - runtime.freeMemory()) / mb);

    this.setTitle(DEFAULT_TITLE + " (" + sampleSize + '/' + cellPanels.size() + ") " + dataSourceName1 + '-'
            + dataSourceName2 + " RAM usage (" + used + "/" + max + ") MB");
}

From source file:com.ibm.bluemix.mobilestarterkit.service.ServiceAPI.java

@Path("/autoscaling")
@POST/*from   www  .j  a va2s.  c o  m*/
public String autoScalingByMem(String param) {
    try {
        JSONObject meta = new JSONObject(param);

        Runtime rt = Runtime.getRuntime();
        int mem_usage = (int) ((rt.totalMemory() * 100.0) / (rt.maxMemory() * 1.0));

        String action = meta.getString("action");

        if ("mem_up".equalsIgnoreCase(action)) {
            // 10M  . Out of memory ?  ?.
            for (int i = 0; i < 10; i++) {
                byte b[] = new byte[1048576];
                v.add(b);
            }
        } else if ("mem_safe_up".equalsIgnoreCase(action) && mem_usage < 90) {
            //   90% ? ?, 10M . OOM 
            for (int i = 0; i < 10; i++) {
                byte b[] = new byte[1048576];
                v.add(b);
            }
        } else if ("mem_reset".equalsIgnoreCase(action)) {
            //  ? 
            v = new Vector();
            rt.gc();
        }
        String msg = "Max " + (rt.maxMemory() / 1000) + " KB  Total used : " + (rt.totalMemory() / 1000)
                + " KB  Free : " + (rt.freeMemory() / 1000) + " KB  "
                + (int) ((rt.totalMemory() * 100.0) / (rt.maxMemory() * 1.0)) + " %";
        System.out.println(msg);
        return msg;

    } catch (JSONException e) {

        e.getStackTrace();
        return "Failed";

    }
}

From source file:elaborate.editor.model.orm.service.ProjectService.java

void logMemory() {
    int mb = 1024 * 1024;
    System.gc();/*from   w w  w.ja va  2  s.c om*/
    // Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();
    Log.info("##### Heap utilization statistics [MB] #####");

    // Print used memory
    Log.info("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

    // Print free memory
    Log.info("Free Memory:" + runtime.freeMemory() / mb);

    // Print total available memory
    Log.info("Total Memory:" + runtime.totalMemory() / mb);

    // Print Maximum available memory
    Log.info("Max Memory:" + runtime.maxMemory() / mb);
}

From source file:org.openmicroscopy.shoola.util.ui.UIUtilities.java

/**
 * Get the free memory available in the system.
 * @return see above./*www  . jav  a 2 s . c  o  m*/
 */
public static long getFreeMemory() {
    Runtime r = Runtime.getRuntime();
    return r.freeMemory();
}

From source file:org.apache.ojb.performance.PerfMain.java

/** Call this to begin the performance test. */
public void startPerfTest(String[] args) throws Exception {
    ArrayList testList = null;/*ww w.j  a v a 2 s  .  c  om*/
    try {
        // comma separated list of the PerfTest implementation classes
        if (args.length > 0) {
            StringTokenizer tok = new StringTokenizer(args[0], ",");
            testList = new ArrayList();
            while (tok.hasMoreTokens()) {
                testList.add(tok.nextToken().trim());
            }
        } else {
            throw new IllegalArgumentException("No test handles found!");
        }
        // number of test loops
        if (args.length > 1) {
            testLoops = args.length > 1 ? Integer.parseInt(args[1]) : 1;
        }
        // number of threads
        if (args.length > 2) {
            concurrentThreads = Integer.parseInt(args[2]);
        }
        // number of insert/fetch/delete loops per thread
        if (args.length > 3) {
            iterationsPerThread = Integer.parseInt(args[3]);
        }
        // run in stress mode
        if (args.length > 4) {
            useStressMode = Boolean.valueOf(args[4]).booleanValue();
        }
        // log mode
        if (args.length > 5) {
            logAll = Boolean.valueOf(args[5]).booleanValue();
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println();
        System.err.println("Usage of PerfMain:"
                + "java -classpath CLASSPATH org.apache.ojb.performance.PerfMain"
                + " [comma separated list of PerfTest implementation classes]" + " [number of test loops]"
                + " [number of threads]" + " [number of insert/fetch/delete loops per thread]"
                + " [boolean - run in stress mode]"
                + " [boolean - if 'true' detailed log messages will be print]");
        System.err.println();
        System.err.println("Example: java -classpath"
                + " CLASSPATH org.apache.ojb.performance.PerfMain org.MyPerfTest 3 10 500 false");
    }

    if (logAll)
        printer().println("                                                    " + EOL
                + "Start OJB performance-test framework - running " + testLoops + " loops" + EOL
                + "-------------------------------------------------------");

    PerfRunner test;
    for (int i = 0; i < testLoops; i++) {
        Runtime rt = Runtime.getRuntime();
        long freeMem;
        if (logAll)
            printer().println(" Loop " + (i + 1));

        if (i % 2 == 0) {
            for (int j = 0; j < testList.size(); j++) {
                String perfTest = (String) testList.get(j);
                Class testHandle = Class.forName(perfTest);
                test = new PerfRunner(testHandle);
                test.registerPerfMain(this);

                rt.gc();
                Thread.sleep(300);
                rt.freeMemory();
                rt.gc();
                Thread.sleep(100);
                freeMem = rt.freeMemory();
                test.performTest();
                freeMem = (freeMem - rt.freeMemory()) / 1024;
                if (logAll)
                    printer().println(" allocated memory=" + freeMem + "kb");
                // rt.gc();
            }
        } else {
            for (int j = (testList.size() - 1); j >= 0; j--) {
                String perfTest = (String) testList.get(j);
                Class testHandle = Class.forName(perfTest);
                test = new PerfRunner(testHandle);
                test.registerPerfMain(this);

                rt.gc();
                Thread.sleep(300);
                rt.freeMemory();
                rt.gc();
                Thread.sleep(100);
                freeMem = rt.freeMemory();
                test.performTest();
                freeMem = (freeMem - rt.freeMemory()) / 1024;
                if (logAll)
                    printer().println(" allocated memory: " + freeMem + " kb");
                // rt.gc();
            }
        }
    }
}

From source file:org.apache.tez.dag.app.TestMockDAGAppMaster.java

private void checkMemory(String name, MockDAGAppMaster mockApp) {
    long mb = 1024 * 1024;

    //Getting the runtime reference from system                                    
    Runtime runtime = Runtime.getRuntime();

    System.out.println("##### Heap utilization statistics [MB] for " + name);

    runtime.gc();/*w w  w  .j a  v a 2  s .c  om*/

    //Print used memory                                                            
    System.out.println("##### Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

    //Print free memory                                                            
    System.out.println("##### Free Memory:" + runtime.freeMemory() / mb);

    //Print total available memory                                                 
    System.out.println("##### Total Memory:" + runtime.totalMemory() / mb);

    //Print Maximum available memory                                               
    System.out.println("##### Max Memory:" + runtime.maxMemory() / mb);
}