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:burstcoin.jminer.core.round.Round.java

private void triggerGarbageCollection() {
    timer.schedule(new TimerTask() {
        @Override//w ww . j a  v a 2 s  . c  o m
        public void run() {
            LOG.debug("trigger garbage collection ... ");
            System.gc();
        }
    }, 1500);
}

From source file:org.fhcrc.cpl.viewer.quant.gui.QuantitationVisualizer.java

/**
 * Iterate through all fractions, finding and visualizing the selected events
 *//*from  w  w  w.j a  va  2s  .co m*/
public void visualizeQuantEvents() throws IOException {
    //trying to prevent memory leaks
    ImageIO.setUseCache(false);

    if (outHtmlFile == null)
        outHtmlFile = new File(outDir, "quantitation.html");
    if (outTsvFile == null)
        outTsvFile = new File(outDir, "quantitation.tsv");

    _log.debug("visualizeQuantEvents begin, write HTML and text? " + writeHTMLAndText);
    if (writeHTMLAndText) {
        outHtmlPW = new PrintWriter(outHtmlFile);
        outTsvPW = new PrintWriter(new FileOutputStream(outTsvFile, appendTsvOutput));
        _log.debug("opened HTML file " + outHtmlFile.getAbsolutePath() + " and tsv file "
                + outTsvFile.getAbsolutePath() + " for writing.");

        //if we're appending, don't write header.  Cheating by writing it to a fake file
        PrintWriter conditionalTsvPW = outTsvPW;
        if (appendTsvOutput && tsvFileAlreadyExists)
            conditionalTsvPW = new PrintWriter(
                    TempFileManager.createTempFile("fake_file", "fake_file_for_quantvisualizer"));

        QuantEvent.writeHeader(outHtmlPW, conditionalTsvPW, showProteinColumn, show3DPlots);
        _log.debug("Wrote HTML and TSV header");
        TempFileManager.deleteTempFiles("fake_file_for_quantvisualizer");
    }

    boolean processedAFraction = false;
    while (featureSetIterator.hasNext()) {
        FeatureSet fraction = featureSetIterator.next();
        ApplicationContext
                .infoMessage("Evaluating fraction " + MS2ExtraInfoDef.getFeatureSetBaseName(fraction));
        if (fractionsToExamine == null
                || fractionsToExamine.contains(MS2ExtraInfoDef.getFeatureSetBaseName(fraction))) {
            ApplicationContext
                    .infoMessage("Handling fraction " + MS2ExtraInfoDef.getFeatureSetBaseName(fraction));
            handleFraction(fraction);
            processedAFraction = true;
        }
        //trying to prevent memory overflow
        System.gc();
    }
    if (!processedAFraction)
        ApplicationContext.infoMessage("WARNING: no fractions processed");
    if (writeHTMLAndText) {
        QuantEvent.writeFooterAndClose(outHtmlPW, outTsvPW);
        ApplicationContext.infoMessage("Saved HTML file " + outHtmlFile.getAbsolutePath());
        ApplicationContext.infoMessage("Saved TSV file " + outTsvFile.getAbsolutePath());
    }

}

From source file:net.sourceforge.dvb.projectx.common.Common.java

public static boolean renameTo(File oldfile, File newfile) {
    //explicit call, otherwise java >= 1.5 ? doesnt release a closed file object immediately
    System.gc();

    for (int i = 0; i < 10000; i++)
        if (oldfile.renameTo(newfile))
            return true;

    setMessage(/*from  w w  w.ja va 2 s  .  c  o m*/
            Resource.getString("common.rename_error1") + " '" + oldfile.toString() + "' "
                    + Resource.getString("common.rename_error2") + " '" + newfile.toString() + "'",
            true, 0xFFE0E0);

    return false;
}

From source file:GridFDock.GridFDockRunner.java

public void executeBlockingJob(final JPPFClient jppfClient) throws Exception {
    /** This part send the 8000 results to nodes. It is likely m*n **/
    // Read the parameters from the file.
    try {/* w ww. j a v  a  2  s  . co m*/
        fl = new File("parameter.mgc");
    } catch (Exception e) {
        System.out.println("The parameter of \"parameter.mgc\" can not be found, please create it!");
    }

    try {
        rd = new BufferedReader(new FileReader(fl));
        userdir = System.getProperty("user.dir");

        while ((tempStr = rd.readLine()) != null) {
            if (tempStr.length() == 0) {
            } else {

                temArray = tempStr.split("\\s+");
                if (temArray[0].equalsIgnoreCase("Ipaddress")) {
                    ip = temArray[1];
                } else if (temArray[0].equalsIgnoreCase("IpPort")) {
                    port = Integer.parseInt(temArray[1]);
                } else if (temArray[0].equalsIgnoreCase("User")) {
                    user = temArray[1];
                } else if (temArray[0].equalsIgnoreCase("Password")) {
                    passwd = temArray[1];
                } else if (temArray[0].equalsIgnoreCase("Downloaddir")) {
                    downdir = temArray[1];
                } else if (temArray[0].equalsIgnoreCase("UploadDir")) {
                    uploaddir = temArray[1];
                } else if (temArray[0].equalsIgnoreCase("Program")) {
                    program = temArray[1];
                } else if (temArray[0].equalsIgnoreCase("Command")) {
                    command = temArray[1];
                } else if (temArray[0].equalsIgnoreCase("Token")) {
                    sign = temArray[1];
                } else if (temArray[0].equalsIgnoreCase("MaxNodes")) {
                    maxNodes = Integer.parseInt(temArray[1]);
                } else if (temArray[0].startsWith("#")) {
                } else {
                    System.out.println("***********: " + tempStr);
                    System.out.println("Configure the wrong parameters in \"parameter.mgc\", please "
                            + "check \"IpPort\", \"User\", \"Password\", \"Downloaddir\", "
                            + "\"UploadDir\", \"Program\", \"Command\" and comments \"#\" so on,"
                            + " and add it according manual!");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Exception happen when read the \"parameter.mgc\", please check the parameters!");
    } finally {
        if (rd != null) {
            rd.close();
        }
    }
    if (ip == null) {
        System.out.println("The FTP ip address should be setting, please check paramter file!");
    } else if (port == 0) {
        System.out.println("The FTP ip port should be setting, please check paramter file!");
    } else if (user == null) {
        System.out.println("The FTP user should be setting, please check paramter file!");
    } else if (passwd == null) {
        System.out.println("The FTP password should be setting, please check paramter file!");
    } else if (downdir == null) {
        System.out.println("The FTP download directory should be setting, please check paramter file!");
    } else if (uploaddir == null) {
        System.out.println("The FTP upload directory should be setting, please check paramter file!");
    } else if (program == null) {
        System.out.println(
                "The run program should be setting such as Autodock_vina etc., please check paramter file!");
    } else if (command == null) {
        System.out
                .println("The program command should be setting such as \"vina\", please check paramter file!");
    } else if (sign == null) {
        System.out.println("The token should be for delete no use files, please check paramter file!");
    } else {
        System.out.println("Every parameter is ok! Now preparing for work!");
    }

    try {
        dt.connect(ip, port, user, passwd);
        if (dt.isconnect() == true) {
            System.out.println("The ftp had connected!");
        } else {
            System.out.println("The ftp can not connect! Please check FTP!");
        }
    } catch (IOException e3) {
        System.out.println("FTP connect err in the server!");
    }

    try {
        // DataDistribute.ftpClient.changeWorkingDirectory(downdir);
        fileList = dt.ftpClient.listFiles(downdir);
    } catch (IOException e) {
        System.out.println("The change working directory is wrong!");
        e.printStackTrace();
    }
    // System.out.println("*****TEST!");
    // The defined contStart and countEnd can be recognized by buildJob function.
    for (int i = 0; i < fileList.length; i = i + maxNodes) {
        countStart = i;
        countEnd = i + maxNodes;
        if (countEnd > fileList.length) {
            countEnd = fileList.length;
        }
        if (maxNodes > fileList.length) {
            tmpCount = fileList.length;
        } else {
            tmpCount = maxNodes;
        }

        // Create a job
        JPPFJob job = buildJob("Virtual Screening job");

        // set the job in blocking mode.
        job.setBlocking(true);

        // Submit the job and wait until the results are returned.
        // The results are returned as a list of Task<?> instances,
        // in the same order as the one in which the tasks where initially added
        // to the job.
        List<Task<?>> results = jppfClient.submitJob(job);
        // process the results
        processExecutionResults(job.getName(), results);

        System.gc();
    }
    dt.disconnect();
}

From source file:cn.edu.zzu.wemall.http.AsyncHttpResponseHandler.java

byte[] getResponseData(HttpEntity entity) throws IOException {
    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }/*from   w  w w  .  java  2 s .co  m*/
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        count += l;
                        buffer.append(tmp, 0, l);
                        sendProgressMessage(count, (int) contentLength);
                    }
                } finally {
                    instream.close();
                }
                responseBody = buffer.buffer();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:net.sourceforge.dvb.projectx.xinput.ftp.XInputFileImpl.java

/**
 * @throws java.io.IOException/*from  w  w w  . j  av  a2  s . c  om*/
 */
public void randomAccessClose() throws IOException {

    if (!isopen) {
        throw new IllegalStateException("XInputFile is already closed!");
    }

    //no need to abort a transfer explicitly, because we logout here

    boolean ret = false;
    if (debug)
        System.out.println("rAC last " + client.getReplyCode() + " / " + client.getReplyString());

    ret = client.isConnected();
    if (debug)
        System.out
                .println("rAC isCon " + ret + " / " + client.getReplyCode() + " / " + client.getReplyString());

    /**
     * alternative kills the client instance, some server won't abort an incomplete data transfer
     * (current box-idx 80)
     */
    if (Common.getSettings().getBooleanProperty(Keys.KEY_killFtpClient)) {
        if (debug)
            System.out.println("rAC kill ");
    }

    /**
     * standard close of a client connection
     */
    else {
        if (!EOF()) {
            if (debug)
                System.out.println("rAC !eof ");

            ret = client.abort();
            if (debug)
                System.out.println(
                        "rAC abort " + ret + " / " + client.getReplyCode() + " / " + client.getReplyString());
        }

        ret = client.logout();
        if (debug)
            System.out.println(
                    "rAC logout " + ret + " / " + client.getReplyCode() + " / " + client.getReplyString());

        ret = client.isConnected();
        if (debug)
            System.out.println(
                    "rAC isCon " + ret + " / " + client.getReplyCode() + " / " + client.getReplyString());

        if (ret) {
            try {
                client.disconnect();
                if (debug)
                    System.out.println("rAC disc " + client.getReplyCode() + " / " + client.getReplyString());
            } catch (IOException e) {
                if (debug)
                    System.out.println("rAC disc-er " + e);
            }
        }
    }

    in = null;
    xIs = null;
    client = null;
    isopen = false;

    System.gc();

    if (debug)
        System.out.println("rAC out ");
}

From source file:com.amalto.workbench.dialogs.ImportExchangeOptionsDialog.java

private void unzipDownloadRes(boolean export) {
    JSONObject datum = dataContent[exchangeDwnTable.getSelectionIndex()];
    InputStream stream = null;/*  w  w w . j  a  v  a 2s.com*/
    OutputStream out = null;
    try {
        String url = datum.getString(COLUMN_URL_NAME);
        stream = HttpClientUtil.getInstreamContentByHttpget(url);
        if (null == stream) {
            throw new RuntimeException("cannot get the content stream"); //$NON-NLS-1$
        }
        String downloadFolder = System.getProperty("user.dir") + File.separator + (export ? "temp" : "xsdTemp");//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
        String subFolderForTmp = downloadFolder + File.separator + "tmp" + System.currentTimeMillis();//$NON-NLS-1$
        File tempFile = new File(subFolderForTmp + File.separator + "tmp" + System.currentTimeMillis());//$NON-NLS-1$

        File dir = new File(downloadFolder);
        if (!dir.exists()) {
            dir.mkdir();
        }
        File subDir = new File(subFolderForTmp);
        if (!subDir.exists()) {
            subDir.mkdir();
        }
        if (zipFileRepository.length() > 0) {
            zipFileRepository.delete(0, zipFileRepository.length());
        }
        out = new FileOutputStream(tempFile);
        IOUtils.copy(stream, out);
        out.flush();
        if (!export) {
            ZipToFile.unZipFile(tempFile.getAbsolutePath(), subFolderForTmp);
            boolean result = false;
            int tryCount = 0;
            while (!result && tryCount++ < 10) {
                System.gc();
                result = tempFile.delete();
            }
            zipFileRepository.append(subFolderForTmp);
        } else {
            zipFileRepository.append(tempFile.getAbsolutePath());
        }
    } catch (Exception e1) {
        final MessageDialog dialog = new MessageDialog(this.getParentShell().getShell(),
                Messages.ImportExchangeOptionsDialog_ParsingError, null, e1.getMessage(), MessageDialog.ERROR,
                new String[] { IDialogConstants.OK_LABEL }, 0);
        dialog.open();
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(stream);
    }
}

From source file:eu.scape_project.planning.xml.ProjectExportAction.java

/**
 * Loads all binary data for the given digital objects and dumps it to XML
 * files, located in tempDir./* w  ww . j  ava2s  . c o m*/
 * 
 * @param objectIds
 * @param tempDir
 * @param encoder
 * @throws IOException
 * @throws StorageException
 */
private void writeBinaryObjects(List<Integer> objectIds, String aTempDir) throws IOException, StorageException {
    int counter = 0;
    int skip = 0;
    log.info("writing XMLs for bytestreams of digital objects. count = " + objectIds.size());
    for (Integer id : objectIds) {
        if (counter > LOADED_DATA_SIZE_BOUNDARY) { // Call GC if unused data
                                                   // exceeds boundary
            System.gc();
            counter = 0;
        }
        DigitalObject object = em.find(DigitalObject.class, id);
        if (object.isDataExistent()) {
            counter += object.getData().getSize();
            File f = new File(aTempDir + object.getId() + ".xml");
            DigitalObject dataFilledObject = null;
            dataFilledObject = digitalObjectManager.getCopyOfDataFilledDigitalObject(object);
            writeBinaryData(id, new ByteArrayInputStream(dataFilledObject.getData().getData()), f);
            dataFilledObject = null;
        } else {
            skip++;
        }
        object = null;
    }
    em.clear();
    System.gc();
    log.info("Finished writing bytestreams of digital objects. Skipped empty objects: " + skip);
}

From source file:com.secretlisa.lib.utils.BaseImageLoader.java

public synchronized Bitmap getBitmapFromCacheFile(String url) {
    String hashedUrl = CommonUtil.md5(url);
    Log.d(TAG, "file md5 = " + hashedUrl);
    FileInputStream fis = null;/*  ww  w. j a  v  a 2  s  .c om*/
    try {
        if (FileUtil.isSdcardValid()
                && FileUtil.fileExist(FileUtil.getFolderPath(getCachePath()) + hashedUrl)) {
            Log.d(TAG, "look from external storage");
            fis = new FileInputStream(new File(FileUtil.getFolderPath(getCachePath()) + hashedUrl));
        } else {
            Log.d(TAG, "look from internal storage");
            fis = mContext.openFileInput(hashedUrl);
        }
        return BitmapFactory.decodeStream(fis);
    } catch (Exception e) {
        Log.e(TAG, "error", e);
        // Not there.
        return null;
    } catch (OutOfMemoryError e) {
        // Not there.
        System.gc();
        clearCache();
        return null;
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                // Ignore.
            }
        }
    }
}

From source file:cn.rongcloud.im.server.network.http.AsyncHttpResponseHandler.java

byte[] getResponseData(HttpEntity entity) throws IOException {
    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }//  w  w  w . j  ava2 s . c om
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        count += l;
                        buffer.append(tmp, 0, l);
                        sendProgressMessage(count, (int) contentLength);
                    }
                } finally {
                    instream.close();
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}