Example usage for java.lang System gc

List of usage examples for java.lang System gc

Introduction

In this page you can find the example usage for java.lang System gc.

Prototype

public static void gc() 

Source Link

Document

Runs the garbage collector in the Java Virtual Machine.

Usage

From source file:org.dkpro.lab.engine.impl.DefaultLifeCycleManager.java

@Override
public void begin(TaskContext aContext, Task aConfiguration) {
    for (int g = 0; g < 3; g++) {
        System.gc();
    }/*from  ww w .j ava 2  s.  c  o  m*/
    aContext.getMetadata().setStart(System.currentTimeMillis());
    aContext.message("Starting task [" + aConfiguration.getType() + "]");
}

From source file:de.escidoc.core.om.performance.Statistics.java

/**
 * @return the statistics of all measured methods.
 *//*from w ww. j  av  a  2 s. c o m*/
@ManagedAttribute(description = "Get all currently available statistics")
public String getKeys() {
    final StringBuilder b = new StringBuilder();
    for (final String key : this.statisticsMap.keySet()) {
        final SummaryStatistics s = getStatistics(key);
        if (s != null) {
            b.append(key).append(", #:").append(s.getN()).append(", min (ms):").append((long) s.getMin())
                    .append(", max (ms):").append((long) s.getMax()).append(", mean (ms):")
                    .append((long) s.getMean()).append(", stddev (ms):").append((long) s.getStandardDeviation())
                    .append(", total (ms):").append((long) s.getSum()).append('\n');
        }
    }
    System.gc();
    return b.toString();
}

From source file:edu.umich.robot.Application.java

/**
 * <p> Loops, running each config file in a batch mode.
 * //from  w ww .j  a v a 2s  .  c  o  m
 * <p> Each run continues until a specified timeout or a number of cycles
 * is exceeded. Both or neither may be specified.  The run also will stop
 * if Soar stops for whatever reason.
 *
 * <p> After a run, the garbage collector is called and the system sleeps
 * for a few seconds. This helps Java manage its memory and threads.
 */
private void multipleRuns(Config config) {
    String[] configs = config.requireStrings("configs");
    int cycles = config.requireInt("cycles");
    int seconds = config.requireInt("seconds");

    for (int i = 0; i < configs.length; ++i) {
        logger.info("Running " + configs[i] + " for " + cycles + " cycles, timeout " + seconds + " seconds.");
        HeadlessApplication h = new HeadlessApplication(toArgs(configs[i]), cycles, seconds);
        if (h.go())
            break;
        logger.info("Done, garbage collect and 5 second sleep.");
        System.gc();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    logger.info("Done.");
}

From source file:com.npower.wurfl.ObjectsManager.java

/**
 * Use this method to force the library to reload the WURFL again
 *///from w  ww.java  2s . c om

public synchronized void reload() {
    wurflInstance = null;
    capabilityMatrixInstance = null;
    UAManagerInstance = null;
    ListManagerInstance = null;
    System.gc();
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.PictureObj.java

public static DbObject from(Context context, Uri imageUri) throws IOException {
    // Query gallery for camera picture via
    // Android ContentResolver interface
    ContentResolver cr = context.getContentResolver();

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/*from  w ww  . j av a 2  s.c  o  m*/
    BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options);

    int targetSize = 200;
    int xScale = (options.outWidth + targetSize - 1) / targetSize;
    int yScale = (options.outHeight + targetSize - 1) / targetSize;

    int scale = xScale < yScale ? xScale : yScale;
    //uncomment this to get faster power of two scaling
    //for(int i = 0; i < 32; ++i) {
    //   int mushed = scale & ~(1 << i);
    //   if(mushed != 0)
    //      scale = mushed;
    //}

    options.inJustDecodeBounds = false;
    options.inSampleSize = scale;

    Bitmap sourceBitmap = BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options);

    int width = sourceBitmap.getWidth();
    int height = sourceBitmap.getHeight();
    int cropSize = Math.min(width, height);

    float scaleSize = ((float) targetSize) / cropSize;

    Matrix matrix = new Matrix();
    matrix.postScale(scaleSize, scaleSize);
    float rotation = PhotoTaker.rotationForImage(context, imageUri);
    if (rotation != 0f) {
        matrix.preRotate(rotation);
    }

    Bitmap resizedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, width, height, matrix, true);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
    byte[] data = baos.toByteArray();
    sourceBitmap.recycle();
    sourceBitmap = null;
    resizedBitmap.recycle();
    resizedBitmap = null;
    System.gc(); // TODO: gross.

    JSONObject base = new JSONObject();
    if (ContentCorral.CONTENT_CORRAL_ENABLED) {
        try {
            String type = cr.getType(imageUri);
            if (type == null) {
                type = "image/jpeg";
            }
            base.put(CorralClient.OBJ_LOCAL_URI, imageUri.toString());
            base.put(CorralClient.OBJ_MIME_TYPE, type);
            String localIp = ContentCorral.getLocalIpAddress();
            if (localIp != null) {
                base.put(Contact.ATTR_LAN_IP, localIp);
            }
        } catch (JSONException e) {
            Log.e(TAG, "impossible json error possible!");
        }
    }
    return from(base, data);
}

From source file:de.juwimm.cms.model.EditionHbmDaoImpl.java

private EditionHbm postCreate(EditionHbm edition, String comment, Integer rootViewComponentId, PrintStream out,
        boolean includeUnused) throws CreateException {
    if (log.isDebugEnabled())
        log.debug("Postcreating Edition");
    if (rootViewComponentId != null) {
        try {/*from  ww  w .j  a  va2 s . c o m*/
            UserHbm creator = getUserHbmDao().load(AuthenticationHelper.getUserName());
            edition.setCreator(creator);
        } catch (Exception exe) {
            log.warn("There went something wrong during ejbPostcreate and finding the right user", exe);
        }
        try {
            ViewComponentHbm vc = getViewComponentHbmDao().load(rootViewComponentId);

            Integer unitId = vc.getUnit4ViewComponent();
            Integer siteId = vc.getViewDocument().getSite().getSiteId();

            out.println("<edition>");

            if (log.isDebugEnabled())
                log.debug("picturesToXmlRecursive");
            this.picturesToXmlRecursive(unitId, siteId, out, edition);
            System.gc();
            if (log.isDebugEnabled())
                log.debug("documentsToXmlRecursive");
            this.documentsToXmlRecursive(unitId, siteId, out, includeUnused, edition);
            System.gc();
            if (vc.isRoot()) { // ROOT Deploy can only be done by a ROOT-User (and this must be automatically invoked!)
                if (log.isDebugEnabled())
                    log.debug("ROOT Deploy");
                this.hostsToXmlRecursive(siteId, out, edition);
                this.shortLinksToXmlRecursive(siteId, out, edition);
                this.unitsToXmlRecursive(siteId, out, edition);
                this.viewdocumentsToXmlRecursive(siteId, out, edition);
                this.realmsToXmlRecursive(siteId, out, edition);
            } else {
                UnitHbm unit = getUnitHbmDao().load(unitId);
                if (log.isDebugEnabled())
                    log.debug("Unit Export/Deploy " + unit.getUnitId() + "(" + unit.getName().trim() + ")");
                out.println("\t<units>");
                if (log.isDebugEnabled())
                    log.debug("unit.toXmlRecursive");
                this.unitsToXmlRecursive(siteId, out, edition);
                //            out.print(unit.toXmlRecursive(2));
                out.println("\t</units>");
                if (log.isDebugEnabled())
                    log.debug("realmsToXmlUsed");
                this.realmsToXmlUsed(unitId, out, edition);
            }
            System.gc();
            if (log.isDebugEnabled())
                log.debug("Creating ViewComponent Data");
            this.viewdocumentsToXmlRecursive(siteId, out, edition);
            //         vc.toXml(vc.getUnit4ViewComponent(), true, false, 0, 0, false, false, out);
            if (log.isDebugEnabled())
                log.debug("Finished creating ViewComponent Data");
            out.println("</edition>");

            edition.setUnitId(vc.getAssignedUnit().getUnitId().intValue());
            edition.setViewDocumentId(vc.getViewDocument().getViewDocumentId().intValue());

            out.flush();
            out.close();
            out = null;
            String siteConfig = vc.getViewDocument().getSite().getConfigXML();
            org.w3c.dom.Document doc = XercesHelper.string2Dom(siteConfig);
            String isEditionLimited = XercesHelper.getNodeValue(doc,
                    "/config/default/parameters/maxEditionStack_1");
            if (isEditionLimited != null && !"".equalsIgnoreCase(isEditionLimited)
                    && Boolean.valueOf(isEditionLimited).booleanValue()) {
                String maxEditionStack = XercesHelper.getNodeValue(doc,
                        "/config/default/parameters/maxEditionStack_2");
                if (maxEditionStack != null && !"".equalsIgnoreCase(maxEditionStack)) {
                    int max = Integer.valueOf(maxEditionStack);
                    // max must be > 0, otherwise the created edition would be deleted before the deploy
                    if (max > 0) {
                        if (log.isDebugEnabled())
                            log.debug("Site: " + siteId + " maxEditionStack: " + max);
                        Collection editions = findByUnitAndViewDocument(vc.getAssignedUnit().getUnitId(),
                                vc.getViewDocument().getViewDocumentId());
                        while (editions.size() > max) {
                            // get oldest edition
                            EditionHbm oldestEdition = null;
                            Iterator edIt = editions.iterator();
                            while (edIt.hasNext()) {
                                EditionHbm currentEdition = (EditionHbm) edIt.next();
                                if ((oldestEdition == null) || (currentEdition.getCreationDate() < oldestEdition
                                        .getCreationDate())) {
                                    oldestEdition = currentEdition;
                                }
                            }
                            if (oldestEdition != null) {
                                // delete oldest one
                                Date oldestCreateDate = new Date(oldestEdition.getCreationDate());
                                if (log.isDebugEnabled())
                                    log.debug("Deleting edition " + oldestEdition.getEditionId() + " of unit \""
                                            + vc.getAssignedUnit().getName().trim() + "\" (" + unitId
                                            + ") from " + sdf.format(oldestCreateDate) + " for language \""
                                            + vc.getViewDocument().getLanguage().trim() + "\"");
                                this.remove(oldestEdition);
                            }
                            editions = this.findByUnitAndViewDocument(vc.getAssignedUnit().getUnitId(),
                                    vc.getViewDocument().getViewDocumentId());
                        }
                    }
                }
            }
        } catch (Exception exe) {
            log.error("Error occured", exe);
        }
    }
    log.debug("Finished Postcreating Edition");
    return edition;
}

From source file:dbs_project.index.performance.IndexTest.java

private /* static */ void printMemory(int scale, IndexType it) {
    for (int i = 0; i < 5; ++i) {
        System.gc();
    }/*  w  w  w  .j  a va 2s  . c  o  m*/
    float footprint = ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024f
            / 1024f);
    this.scaleResults.add("<measurement><name>footprint</name>" + "<scale>" + scale + "</scale>" + "<type>" + it
            + "</type>" + "<value>" + footprint + "</value></measurement>");
    Utils.getOut().println("Memory footprint: " + footprint + " MB");
}

From source file:com.plugin.gallery.ForegroundGalleryLauncher.java

/**
 * Called when the camera view exits.//from  ww w .  j a v a  2s.co m
 * 
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param intent
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if (resultCode == Activity.RESULT_OK) {

        Uri uri = intent.getData();
        String fileURL = intent.getStringExtra("fileURL");
        System.out.println("fileURL = " + fileURL);
        ContentResolver resolver = this.cordova.getActivity().getContentResolver();

        try {
            Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            bitmap = scaleBitmap(bitmap);
            this.processPicture(bitmap);
            bitmap.recycle();
            bitmap = null;
            this.callbackContext.success("" + fileURL);
            System.gc();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            this.failPicture("Error retrieving image.");
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Selection cancelled.");
    } else {
        this.failPicture("Selection did not complete!");
    }
}

From source file:com.tesora.dve.standalone.PETest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    delay("running test class", "beforeClass.delay", 0L);

    applicationName = "PETest";

    //SMG://  w w w  .  j a va  2s. co m
    //      System.setProperty(ResourceLeakDetector.SYSTEM_ENABLE_LEAK_DETECTION, "true");
    //      System.setProperty(ResourceLeakDetector.SYSTEM_LEAK_DETECTION_INTERVAL, "1");
    //      System.setProperty(ResourceLeakDetector.SYSTEM_REPORT_ALL, "true");
    //
    leakCount = NettyLeakIntercept.installLeakTrap();
    System.gc();
    long leaks = leakCount.clearEmittedLeakCount();
    if (leaks != 0) {
        throw new Exception("Starting subclass of PETest, and initial buffer leak counter was non-zero ==> "
                + leaks
                + ".  Inspect slf4j output for netty leak errors, and consider re-running tests with -Dio.netty.leakDetectionLevel=PARANOID");
    }

    logger = Logger.getLogger(PETest.class);

    if (stateUndoer == null)
        stateUndoer = new GlobalVariableState();
}

From source file:com.univocity.app.DataUpdateTest.java

@Test(dataProvider = "absentProvider", dependsOnMethods = "testDataUpdate")
public void testDeleteAbsent(EntityMapping mapping, RowDataCollector dataCollector, String entityName,
        String insertFile, String updateFile, String deleteFile) {
    System.gc();
    mapping.persistence().usingMetadata().deleteAbsent().updateDisabled().insertDisabled();
    loadProcess.execute(entityName);/*  www  .  ja  v  a  2  s. co m*/
    validateAbsentRecordsGotRemoved(entityName, dataCollector, deleteFile);
    System.gc();
}