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:edu.upenn.ircs.lignos.morsel.MorphLearner.java

private String memoryStatus() {
    // Check the memory
    Runtime runtime = Runtime.getRuntime();
    long usage = runtime.totalMemory() - runtime.freeMemory();
    long remaining = runtime.maxMemory() - usage;

    // Conver to megabytes
    usage /= 1048576L;//from  www  .ja va  2  s  .co m
    remaining /= 1048576L;

    return "Memory status: " + usage + "MB Used, " + remaining + "MB Remaining";
}

From source file:org.janusgraph.diskstorage.Backend.java

/**
 * Initializes this backend with the given configuration. Must be called before this Backend can be used
 *
 * @param config/*from   w  ww .  j a  va2 s  . c om*/
 */
public void initialize(Configuration config) {
    try {
        //EdgeStore & VertexIndexStore
        KeyColumnValueStore idStore = storeManager.openDatabase(ID_STORE_NAME);

        idAuthority = null;
        if (storeFeatures.isKeyConsistent()) {
            idAuthority = new ConsistentKeyIDAuthority(idStore, storeManager, config);
        } else {
            throw new IllegalStateException(
                    "Store needs to support consistent key or transactional operations for ID manager to guarantee proper id allocations");
        }

        KeyColumnValueStore edgeStoreRaw = storeManagerLocking.openDatabase(EDGESTORE_NAME);
        KeyColumnValueStore indexStoreRaw = storeManagerLocking.openDatabase(INDEXSTORE_NAME);

        //Configure caches
        if (cacheEnabled) {
            long expirationTime = configuration.get(DB_CACHE_TIME);
            Preconditions.checkArgument(expirationTime >= 0, "Invalid cache expiration time: %s",
                    expirationTime);
            if (expirationTime == 0)
                expirationTime = ETERNAL_CACHE_EXPIRATION;

            long cacheSizeBytes;
            double cachesize = configuration.get(DB_CACHE_SIZE);
            Preconditions.checkArgument(cachesize > 0.0, "Invalid cache size specified: %s", cachesize);
            if (cachesize < 1.0) {
                //Its a percentage
                Runtime runtime = Runtime.getRuntime();
                cacheSizeBytes = (long) ((runtime.maxMemory() - (runtime.totalMemory() - runtime.freeMemory()))
                        * cachesize);
            } else {
                Preconditions.checkArgument(cachesize > 1000, "Cache size is too small: %s", cachesize);
                cacheSizeBytes = (long) cachesize;
            }
            log.info("Configuring total store cache size: {}", cacheSizeBytes);
            long cleanWaitTime = configuration.get(DB_CACHE_CLEAN_WAIT);
            Preconditions.checkArgument(EDGESTORE_CACHE_PERCENT + INDEXSTORE_CACHE_PERCENT == 1.0,
                    "Cache percentages don't add up!");
            long edgeStoreCacheSize = Math.round(cacheSizeBytes * EDGESTORE_CACHE_PERCENT);
            long indexStoreCacheSize = Math.round(cacheSizeBytes * INDEXSTORE_CACHE_PERCENT);

            edgeStore = new ExpirationKCVSCache(edgeStoreRaw, getMetricsCacheName(EDGESTORE_NAME),
                    expirationTime, cleanWaitTime, edgeStoreCacheSize);
            indexStore = new ExpirationKCVSCache(indexStoreRaw, getMetricsCacheName(INDEXSTORE_NAME),
                    expirationTime, cleanWaitTime, indexStoreCacheSize);
        } else {
            edgeStore = new NoKCVSCache(edgeStoreRaw);
            indexStore = new NoKCVSCache(indexStoreRaw);
        }

        //Just open them so that they are cached
        txLogManager.openLog(SYSTEM_TX_LOG_NAME);
        mgmtLogManager.openLog(SYSTEM_MGMT_LOG_NAME);
        txLogStore = new NoKCVSCache(storeManager.openDatabase(SYSTEM_TX_LOG_NAME));

        //Open global configuration
        KeyColumnValueStore systemConfigStore = storeManagerLocking.openDatabase(SYSTEM_PROPERTIES_STORE_NAME);
        systemConfig = getGlobalConfiguration(new BackendOperation.TransactionalProvider() {
            @Override
            public StoreTransaction openTx() throws BackendException {
                return storeManagerLocking.beginTransaction(StandardBaseTransactionConfig
                        .of(configuration.get(TIMESTAMP_PROVIDER), storeFeatures.getKeyConsistentTxConfig()));
            }

            @Override
            public void close() throws BackendException {
                //Do nothing, storeManager is closed explicitly by Backend
            }
        }, systemConfigStore, configuration);
        userConfig = getConfiguration(new BackendOperation.TransactionalProvider() {
            @Override
            public StoreTransaction openTx() throws BackendException {
                return storeManagerLocking.beginTransaction(
                        StandardBaseTransactionConfig.of(configuration.get(TIMESTAMP_PROVIDER)));
            }

            @Override
            public void close() throws BackendException {
                //Do nothing, storeManager is closed explicitly by Backend
            }
        }, systemConfigStore, USER_CONFIGURATION_IDENTIFIER, configuration);

    } catch (BackendException e) {
        throw new JanusGraphException("Could not initialize backend", e);
    }
}

From source file:uk.ac.ebi.phenotype.solr.indexer.IndexerManager.java

/**
 * Print the jvm memory configuration./*from w w w . j ava2 s . c  o  m*/
 */
private void printJvmMemoryConfiguration() {
    final int mb = 1024 * 1024;
    Runtime runtime = Runtime.getRuntime();
    DecimalFormat formatter = new DecimalFormat("#,###");
    logger.info("Used memory : " + (formatter.format(runtime.totalMemory() - runtime.freeMemory() / mb)));
    logger.info("Free memory : " + formatter.format(runtime.freeMemory()));
    logger.info("Total memory: " + formatter.format(runtime.totalMemory()));
    logger.info("Max memory  : " + formatter.format(runtime.maxMemory()));
}

From source file:org.mrgeo.resources.wms.WmsGenerator.java

private Response handleRequest(@Context UriInfo uriInfo) {
    long start = System.currentTimeMillis();
    try {/*from   w ww  . j av a 2 s . c om*/
        MultivaluedMap<String, String> allParams = uriInfo.getQueryParameters();
        String request = getQueryParam(allParams, "request", "GetCapabilities");
        ProviderProperties providerProperties = SecurityUtils.getProviderProperties();

        String serviceName = getQueryParam(allParams, "service");
        if (serviceName == null) {
            return writeError(Response.Status.BAD_REQUEST,
                    "Missing required SERVICE parameter. Should be set to \"WMS\"");
        }
        if (!serviceName.equalsIgnoreCase("wms")) {
            return writeError(Response.Status.BAD_REQUEST,
                    "Invalid SERVICE parameter. Should be set to \"WMS\"");
        }

        if (request.equalsIgnoreCase("getmap")) {
            return getMap(allParams, providerProperties);
        } else if (request.equalsIgnoreCase("getmosaic")) {
            return getMosaic(allParams, providerProperties);
        } else if (request.equalsIgnoreCase("gettile")) {
            return getTile(allParams, providerProperties);
        } else if (request.equalsIgnoreCase("getcapabilities")) {
            return getCapabilities(uriInfo, allParams, providerProperties);
        } else if (request.equalsIgnoreCase("describetiles")) {
            return describeTiles(uriInfo, allParams, providerProperties);
        }
        return writeError(Response.Status.BAD_REQUEST, "Invalid request");
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("WMS request time: {}ms", (System.currentTimeMillis() - start));
            // this can be resource intensive.
            System.gc();
            final Runtime rt = Runtime.getRuntime();
            log.debug(String.format("WMS request memory: %.1fMB / %.1fMB\n",
                    (rt.totalMemory() - rt.freeMemory()) / 1e6, rt.maxMemory() / 1e6));
        }
    }
}

From source file:com.ettrema.zsync.IntegrationTests.java

/**
 * Constructs an UploadMaker/UploadMakerEx, saves the Upload stream to a new File with
 * name uploadFileName, and returns that File.
 * /*  ww w  . j a  v  a2  s. c om*/
 * @param localFile The local file to be uploaded
 * @param zsFile The zsync of the server file
 * @param uploadFileName The name of the File in which to save the upload stream
 * @return
 * @throws IOException
 */
private File makeAndSaveUpload(File localFile, File zsFile, String uploadFileName) throws IOException {
    System.out.println("------------- makeAndSaveUpload --------------------");

    System.gc();
    Runtime rt = Runtime.getRuntime();

    UploadMaker umx = new UploadMaker(localFile, zsFile);
    InputStream uploadIn = umx.makeUpload();

    File uploadFile = new File(uploadFileName);

    if (uploadFile.exists()) {
        if (!uploadFile.delete()) {
            throw new RuntimeException("Couldnt delete: " + uploadFile.getAbsolutePath());
        }
    }
    FileOutputStream uploadOut = new FileOutputStream(uploadFile);

    System.gc();
    System.out.println("Memory stats: " + formatBytes(rt.maxMemory()) + " - " + formatBytes(rt.totalMemory())
            + " - " + formatBytes(rt.freeMemory()));
    long endUsed = (rt.totalMemory() - rt.freeMemory());
    System.out.println("Start used memory: " + formatBytes(startUsed) + " end used memory: "
            + formatBytes(endUsed) + " - delta: " + formatBytes(endUsed - startUsed));
    System.out.println("");

    IOUtils.copy(uploadIn, uploadOut);
    uploadIn.close();
    uploadOut.close();

    System.out.println("Created upload of size: " + formatBytes(uploadFile.length()) + " from local file: "
            + formatBytes(localFile.length()));

    return uploadFile;

}

From source file:spade.reporter.CDM.java

private void printStats() {
    Runtime runtime = Runtime.getRuntime();
    long usedMemoryMB = (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024);
    long internalBufferSize = getBuffer().size();
    logger.log(Level.INFO, "Lines read: {0}, Internal buffer size: {1}, JVM memory in use: {2}MB",
            new Object[] { linesRead, internalBufferSize, usedMemoryMB });
}

From source file:net.sf.nmedit.nomad.core.Nomad.java

public void debug_gc() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Runtime rt = Runtime.getRuntime();
            System.out.println("garbage collect");
            System.gc();//from  www .j av  a2 s .co m
            System.out.println("gc: free:" + rt.freeMemory() + " byte, max:" + rt.maxMemory());
        }
    });
}

From source file:im.neon.activity.CommonActivityUtils.java

/**
 * Log the memory statuses./* w w w  . j a v a  2  s  . com*/
 *
 * @param activity the calling activity
 * @return if the device is running on low memory.
 */
public static boolean displayMemoryInformation(Activity activity, String title) {
    long freeSize = 0L;
    long totalSize = 0L;
    long usedSize = -1L;
    try {
        Runtime info = Runtime.getRuntime();
        freeSize = info.freeMemory();
        totalSize = info.totalMemory();
        usedSize = totalSize - freeSize;
    } catch (Exception e) {
        e.printStackTrace();
    }

    Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");
    Log.e(LOW_MEMORY_LOG_TAG, "----------- " + title + " -----------------");
    Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");
    Log.e(LOW_MEMORY_LOG_TAG, "usedSize   " + (usedSize / 1048576L) + " MB");
    Log.e(LOW_MEMORY_LOG_TAG, "freeSize   " + (freeSize / 1048576L) + " MB");
    Log.e(LOW_MEMORY_LOG_TAG, "totalSize  " + (totalSize / 1048576L) + " MB");
    Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");

    if (null != activity) {
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);

        Log.e(LOW_MEMORY_LOG_TAG, "availMem   " + (mi.availMem / 1048576L) + " MB");
        Log.e(LOW_MEMORY_LOG_TAG, "totalMem   " + (mi.totalMem / 1048576L) + " MB");
        Log.e(LOW_MEMORY_LOG_TAG, "threshold  " + (mi.threshold / 1048576L) + " MB");
        Log.e(LOW_MEMORY_LOG_TAG, "lowMemory  " + (mi.lowMemory));
        Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");
        return mi.lowMemory;
    } else {
        return false;
    }
}

From source file:tectonicus.world.World.java

public void dumpMemStats() {
    System.out.println("---------------");
    System.out.println("World Mem Stats");
    System.out.println("---------------");

    //   System.out.println("Total chunks: "+chunks.size());
    System.out.println("Loaded raw chunks: " + rawLoadedChunks.size());
    System.out.println("Loaded geometry chunks: " + geometryLoadedChunks.size());

    long rawMemTotal = rawLoadedChunks.getRawMemorySize();
    rawMemTotal = rawMemTotal / 1024 / 1024; // bytes to megabytes
    System.out.println("Estimated raw memory: " + rawMemTotal + " Mb");

    long geometryMemTotal = geometryLoadedChunks.getGeometryMemorySize();
    geometryMemTotal = geometryMemTotal / 1024 / 1024; // bytes to megabytes
    System.out.println("Estimated geometry memory: " + geometryMemTotal + " Mb");

    System.out.println();/*  ww  w .jav  a 2  s .co  m*/

    Runtime runtime = Runtime.getRuntime();

    final long maxMemory = runtime.maxMemory();
    final long allocatedMemory = runtime.totalMemory();
    final long freeMemory = runtime.freeMemory();

    NumberFormat format = NumberFormat.getInstance();
    System.out.println("Max memory: " + format.format(maxMemory / 1024.0f) + "Mb");
    System.out.println("Allocated memory: " + format.format(allocatedMemory / 1024.0f) + "Mb");
    System.out.println("Free memory: " + format.format(freeMemory / 1024.0f) + "Mb");

    /*
    System.out.println("Geometry stats:");
    for (Chunk c : geometryLoadedChunks.values())
    {
       c.printGeometryStats();
    }
    */
}

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

/**
 * Read one Resource from xml/*from w ww.j a  va2 s  .c om*/
 * 
 * @param xml
 *        An string containing the xml which describes the resource.
 * @return The Resource object created from the xml.
 */
protected Entity readResource(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, null, 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");
        }

    }
}