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:com.futurologeek.smartcrossing.crop.CropImageActivity.java

private void setupViews() {
    setContentView(R.layout.crop__activity_crop);
    wholeRelative = (RelativeLayout) findViewById(R.id.whole_relative);

    imageView = (CropImageView) findViewById(R.id.crop_image);
    imageView.context = this;
    imageView.setRecycler(new ImageViewTouchBase.Recycler() {
        @Override/*  ww w  .j a va2  s.  c  o m*/
        public void recycle(Bitmap b) {
            b.recycle();
            System.gc();
        }
    });

    findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            setResult(RESULT_CANCELED);
            finish();
        }
    });

    findViewById(R.id.btn_done).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            onSaveClicked();
        }
    });
}

From source file:net.lightbody.bmp.proxy.jetty.http.ResourceCache.java

public void flushCache() {
    _cache.clear();
    System.gc();
}

From source file:gov.nist.appvet.tool.AsynchronousService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = null;// w  w w .j av a 2 s.c  om
    FileItem fileItem = null;
    String appId = null;

    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // Get form fields
    Iterator iter = items.iterator();
    FileItem item = null;
    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (item.isFormField()) {
            String incomingParameter = item.getFieldName();
            String incomingValue = item.getString();
            if (incomingParameter.equals("appid")) {
                appId = incomingValue;
            }
            log.debug("Received: " + incomingParameter + " = " + incomingValue);
        } else {
            // item should now hold the received file
            if (item != null) {
                fileItem = item;
            }
        }
    }

    // If app ID and file were received, send back HTTP 202 now
    if (appId != null && fileItem != null) {
        sendHttp202(response, "Received app " + appId + " for processing.");
    } else {
        sendHttp400(response, "Did not receive proper request.");
        return;
    }

    String appFilePath = null;
    String reportPath = null;
    String fileName = null;

    if (item != null) {
        fileName = getFileName(fileItem.getName());
        if (!fileName.endsWith(".apk")) {
            sendHttp400(response, "Invalid app file: " + fileItem.getName());
            return;
        }

        appFilePath = Properties.TEMP_DIR + "/" + appId + fileName;
        reportPath = Properties.TEMP_DIR + "/" + appId + "_report.txt";
        log.debug("appFilePath: " + appFilePath);

        if (!saveFileUpload(fileItem, appFilePath)) {
            sendHttp500(response, "Could not save uploaded file");
            return;
        }
    } else {
        log.error("File item was null.");
        return;
    }

    // Test app
    AndroidVulnerabilityScanner vulnerabilityScanner = new AndroidVulnerabilityScanner(appFilePath);

    boolean masterKeyFound = vulnerabilityScanner.hasMasterKey();

    boolean extraFieldFound = vulnerabilityScanner.hasExtraField();
    vulnerabilityScanner.close();

    // Generate report
    String htmlReport = null;
    ToolStatus reportStatus = null;
    if (masterKeyFound) {
        reportStatus = ToolStatus.FAIL;
        htmlReport = generateReport(fileName, reportStatus, "Master Key vulnerability detected.");
    }
    if (extraFieldFound) {
        reportStatus = ToolStatus.FAIL;
        htmlReport = generateReport(fileName, reportStatus, "Extra Field vulnerability detected.");
    }

    if (!masterKeyFound && !extraFieldFound) {
        reportStatus = ToolStatus.PASS;
        htmlReport = generateReport(fileName, reportStatus,
                "No Master Key or Extra Field vulnerablity detected.");
    }

    // Write report file
    PrintWriter out = new PrintWriter(reportPath);
    out.write(htmlReport);
    out.close();

    // Now send report
    sendReport(appId, reportStatus.name(), reportPath);

    boolean deleted = deleteFile(appFilePath);
    if (deleted) {
        log.debug("Deleted app " + appFilePath);
    } else {
        log.error("Could not delete app file " + appFilePath);
    }

    deleted = deleteFile(reportPath);
    if (deleted) {
        log.debug("Deleted report " + reportPath);
    } else {
        log.error("Could not delete report file " + reportPath);
    }

    // Clean up
    System.gc();
}

From source file:com.intuit.wasabi.tests.service.assignment.SingleAssignmentContextTest.java

/**
 * The below method tears down the test experiments that are created that we stored using the testExperimentsList
 */// w ww .ja  v  a  2 s  .c o m
@AfterClass()
public void tearDown() {
    for (Experiment exp : testExperimentsList) {
        exp.state = Constants.EXPERIMENT_STATE_PAUSED;
        putExperiment(exp);

        // delete the experiment
        exp.state = Constants.EXPERIMENT_STATE_TERMINATED;
        putExperiment(exp);
    }

    // lets dereference the list and call the Garbage collector Daemon
    testExperimentsList = null;
    System.gc();
}

From source file:com.elastica.helper.FileUtility.java

/**
 * Constructs ImageElement from bytes and stores it.
 *
 * @param  path//w w w. j a  v  a 2 s  . c  om
 */
public static synchronized void writeImage(final String path, final byte[] byteArray) {
    if (byteArray.length == 0) {
        return;
    }

    System.gc();

    InputStream in = null;
    FileOutputStream fos = null;
    try {
        File parentDir = new File(path).getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        byte[] decodeBuffer = Base64.decodeBase64(byteArray);
        in = new ByteArrayInputStream(decodeBuffer);

        BufferedImage img = ImageIO.read(in);
        fos = new FileOutputStream(path);
        ImageIO.write(img, "png", fos);
        img = null;
    } catch (Exception e) {
        logger.warn(e.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.openmrs.module.idcards.web.servlet.PrintEmptyIdcardsServlet.java

/**
 * Write the pdf to the given response/*from   w  w w  . jav a 2 s  .c om*/
 */
@SuppressWarnings("unchecked")
public static void generateOutputForIdentifiers(IdcardsTemplate card, String baseURL,
        HttpServletResponse response, List<String> identifiers, String password)
        throws ServletException, IOException {

    Properties props = new Properties();
    props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
    props.setProperty("class.resource.loader.description", "VelocityClasspathResourceLoader");
    props.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
            "org.apache.velocity.runtime.log.NullLogSystem");

    // do the velocity magic
    Writer writer = new StringWriter();
    try {
        // Allow images to be served from Unix servers.
        try {
            java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
        } catch (Throwable t) {
            log.warn(
                    "Unable to get graphics environment.  "
                            + "Make sure that -Djava.awt.headless=true is defined as a JAVA OPT during startup",
                    t);
        }
        Velocity.init(props);
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("locale", Context.getLocale());
        velocityContext.put("identifiers", identifiers);
        velocityContext.put("baseURL", baseURL);
        Velocity.evaluate(velocityContext, writer, PrintEmptyIdcardsServlet.class.getName(), card.getXml());
    } catch (ParseErrorException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (MethodInvocationException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (ResourceNotFoundException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (Exception e) {
        throw new ServletException("Error initializing Velocity engine", e);
    } finally {
        System.gc();
    }

    try {
        //Setup a buffer to obtain the content length
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        FopFactory fopFactory = FopFactory.newInstance();

        //fopFactory supports customization with a config file
        //Load the config file before creating the user agent.
        String userConfigFile = Context.getAdministrationService()
                .getGlobalProperty("idcards.fopConfigFilePath");
        if (userConfigFile != null) {
            try {
                fopFactory.setUserConfig(new java.io.File(userConfigFile));
                log.debug("Successfully loaded config file |" + userConfigFile + "|");
            } catch (Exception e) {
                log.error("Could not initialize fopFactory user config with file at " + userConfigFile
                        + ". Error message:" + e.getMessage());
            }
        }

        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        foUserAgent.getRendererOptions().put("encryption-params",
                new PDFEncryptionParams(password, null, true, false, false, false));

        //Setup FOP
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        //Setup Transformer
        Source xsltSrc = new StreamSource(new StringReader(card.getXslt()));
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(xsltSrc);

        //Make sure the XSL transformation's result is piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        //Setup input
        String xml = writer.toString();
        Source src = new StreamSource(new StringReader(xml));

        //Start the transformation and rendering process
        transformer.transform(src, res);

        //Prepare response
        String time = new SimpleDateFormat("yyyy-MM-dd_Hms").format(new Date());
        String filename = card.getName().replace(" ", "_") + "-" + time + ".pdf";
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        response.setContentType("application/pdf");
        response.setContentLength(out.size());

        //Send content to Browser
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(out.toByteArray());
        outputStream.flush();
    } catch (FOPException e) {
        throw new ServletException("Error generating report", e);
    } catch (TransformerConfigurationException e) {
        throw new ServletException("Error generating report", e);
    } catch (TransformerException e) {
        throw new ServletException("Error generating report", e);
    }
}

From source file:com.chtr.tmoauto.webui.CommonFunctions.java

/**
 * This method build and return a webDriver instance by which one can use to control the automation of a specified
 * web browser and platform or Operating System.
 *
 * @param url - main test url/* w ww .ja va 2s.c  om*/
 * @param browserType - type of browser to automate
 * @param platform - operating system or platform type
 * @param seleniumGridUrl - selenium Grid Url
 * @return
 * @return - Instance of WebBrowser
 */
@SuppressWarnings("resource")
public static CommonFunctions buildRemoteWebDriver(String url, String browserName, Method method) {
    Annotation[] a = method.getAnnotations();
    String description = null;
    try {
        description = a[0].toString().split("description=")[1].split(", retryAnalyzer=")[0];
    } catch (Exception e) {
    }
    System.gc();
    log.info("");
    log.info("=========================================================");
    log.info("Test: {}", method.getName());
    log.info("Test Description: {}", description);
    log.info("=========================================================");
    WebDriver wd = buildRemoteWebDriver(browserName);
    CommonFunctions wDriver = new CommonFunctions(wd);
    log.info("Starting Remote WebDriver: { Browser: {} } { Version: {} } { Platform: {} } ",
            wDriver.getBrowserName().trim(), wDriver.getBrowserVersion().trim(),
            wDriver.discoverPlatform().toString());
    log.info("Navigating to: {}", url);
    wd.get(url);
    return new CommonFunctions(wd);
}

From source file:gov.nih.nci.caarray.plugins.affymetrix.CelHandler.java

/**
 * @param filename/* www  . ja va 2s .  c  o  m*/
 */
private boolean readCelData(final String filename) {
    this.celData.setFileName(filename);
    boolean success = this.celData.read();
    if (!success) {
        // This invokes a fileChannel.map call that could possibly fail due to a bug in Java
        // that causes previous memory mapped files to not be released until after GC. So
        // we force a gc here to ensure that is not the cause of our problems
        this.celData.close();
        this.celData.clear();
        System.gc();
        success = this.celData.read();
    }
    return success;
}

From source file:fr.inria.wimmics.coresetimer.CoreseTimer.java

private long getMemoryUsage() {
    long before = getGcCount();
    System.gc();
    while (getGcCount() == before)
        ;// w  w  w .  ja  v  a2  s  .co m
    return getCurrentlyUsedMemory();
}

From source file:de.fosd.jdime.strategy.CombinedStrategy.java

/**
 * TODO: high-level documentation//from   ww w. jav a  2 s.  c o m
 * @param operation
 * @param context
 *
 * @throws IOException
 * @throws InterruptedException
 */
@Override
public final void merge(final MergeOperation<FileArtifact> operation, final MergeContext context)
        throws IOException, InterruptedException {
    assert (operation != null);
    assert (context != null);

    context.resetStreams();

    FileArtifact target = null;

    if (!context.isDiffOnly() && operation.getTarget() != null) {
        assert (operation.getTarget() instanceof FileArtifact);
        target = operation.getTarget();
        assert (!target.exists() || target.isEmpty()) : "Would be overwritten: " + target;
    }

    if (LOG.isInfoEnabled()) {
        MergeTriple<FileArtifact> triple = operation.getMergeTriple();
        assert (triple != null);
        assert (triple.isValid()) : "The merge triple is not valid!";
        LOG.info("Merging: " + triple.getLeft().getPath() + " " + triple.getBase().getPath() + " "
                + triple.getRight().getPath());
    }

    ArrayList<Long> runtimes = new ArrayList<>();
    MergeContext subContext = null;
    Stats substats = null;

    for (int i = 0; i < context.getBenchmarkRuns() + 1 && (i == 0 || context.isBenchmark()); i++) {
        long cmdStart = System.currentTimeMillis();
        subContext = (MergeContext) context.clone();
        subContext.setOutputFile(null);

        if (LOG.isInfoEnabled() && i == 0) {
            LOG.info("Trying linebased strategy.");
        }

        MergeStrategy<FileArtifact> s = new LinebasedStrategy();
        subContext.setMergeStrategy(s);
        subContext.setSaveStats(true);
        s.merge(operation, subContext);

        int conflicts = subContext.getStats().getConflicts();
        if (conflicts > 0) {
            // merge not successful. we need another strategy.
            if (LOG.isInfoEnabled() && i == 0) {
                String noun = conflicts > 1 ? "conflicts" : "conflict";
                LOG.info("Got " + conflicts + " " + noun + ". Need to use structured strategy.");
            }

            // clean target file
            if (LOG.isInfoEnabled()) {
                LOG.info("Deleting: " + target);
            }

            if (target != null) {
                boolean isLeaf = target.isLeaf();
                target.remove();
                target.createArtifact(isLeaf);
            }

            subContext = (MergeContext) context.clone();
            subContext.setOutputFile(null);

            s = new StructuredStrategy();
            subContext.setMergeStrategy(s);
            if (i == 0) {
                subContext.setSaveStats(true);
            } else {
                subContext.setSaveStats(false);
                subContext.setBenchmark(true);
                subContext.setBenchmarkRuns(0);
            }
            s.merge(operation, subContext);
        } else {
            if (LOG.isInfoEnabled() && i == 0) {
                LOG.info("Linebased strategy worked fine.");
            }
        }

        if (i == 0) {
            substats = subContext.getStats();
        }

        long runtime = System.currentTimeMillis() - cmdStart;
        runtimes.add(runtime);

        if (LOG.isInfoEnabled() && context.isBenchmark()) {
            if (i == 0) {
                LOG.info("Initial run: " + runtime + " ms");
            } else {
                LOG.info("Run " + i + " of " + context.getBenchmarkRuns() + ": " + runtime + " ms");
            }
        }
    }

    if (context.isBenchmark() && runtimes.size() > 1) {
        // remove first run as it took way longer due to all the counting
        runtimes.remove(0);
    }

    Long runtime = MergeContext.median(runtimes);
    LOG.debug("Combined merge time was " + runtime + " ms.");

    assert (subContext != null);

    if (subContext.hasOutput()) {
        context.append(subContext.getStdIn());
    }

    if (subContext.hasErrors()) {
        context.appendError(subContext.getStdErr());
    }

    // write output
    if (target != null) {
        assert (target.exists());
        target.write(context.getStdIn());
    }

    // add statistical data to context
    if (context.hasStats()) {
        assert (substats != null);

        Stats stats = context.getStats();
        substats.setRuntime(runtime);
        MergeTripleStats subscenariostats = substats.getScenariostats().remove(0);
        assert (substats.getScenariostats().isEmpty());

        if (subscenariostats.hasErrors()) {
            stats.addScenarioStats(subscenariostats);
        } else {
            MergeTripleStats scenariostats = new MergeTripleStats(subscenariostats.getTriple(),
                    subscenariostats.getConflicts(), subscenariostats.getConflictingLines(),
                    subscenariostats.getLines(), runtime, subscenariostats.getASTStats(),
                    subscenariostats.getLeftASTStats(), subscenariostats.getRightASTStats());
            stats.addScenarioStats(scenariostats);
        }

        context.addStats(substats);
    }
    System.gc();
}