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.amalto.workbench.utils.LocalTreeObjectRepository.java

private boolean forceDelete() {
    File configFile = new File(config);
    boolean result = false;
    int tryCount = 0;
    while (!result && tryCount++ < 10) {
        System.gc();
        result = configFile.delete();//from  w  ww  . ja  va 2  s  .c  om
    }

    if (result) {
        MessageDialog.openWarning(null, Messages.LocalTreeObjectRepository_ErrorTitle,
                Messages.LocalTreeObjectRepository_ErrorMsg);
    }

    return result;
}

From source file:FTP.FileUploading.java

@Override
public void run() {
    try {/*from w  ww.  ja  v a  2 s.  c o m*/
        File secondLocalFile = new File(this.LocalFile);
        SizeFile(secondLocalFile, "KB");
        //            long size = secondLocalFile.length();
        long size = 0x00FFFFFF;

        String secondRemoteFile = this.RemotFile;
        inputStream = new FileInputStream(secondLocalFile);

        try (OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile)) {
            byte[] bytesIn = new byte[(int) size];
            int read = 0;
            ComSpy.MessageLog("Start To Uploading " + this.LocalFile + " Length : " + secondLocalFile.length());
            while ((read = inputStream.read(bytesIn)) != -1) {
                outputStream.write(bytesIn, 0, read);
            }

            Thread.sleep(200);

            inputStream.close();
            outputStream.flush();
            ComSpy.MessageLog("Copy Data is Done");
            completed = true;
            if (completed) {
                ComSpy.MessageLog("Upload Done " + this.RemotFile);
                //                secondLocalFile.delete();
                Done = true;
            }
        }

        System.gc();
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
        this.RemotFile = this.LocalFile;
        Done = true;
        this.interrupt();
    } catch (InterruptedException ex) {
        System.err.println("Interrupted " + ex.getMessage());
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
                this.interrupt();
            }
        } catch (IOException ex) {
            this.interrupt();
        }
    }
}

From source file:com.panet.imeta.job.entries.deletefile.JobEntryDeleteFile.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);/*w  ww  .  j  a  va 2  s .  c o  m*/

    if (filename != null) {
        String realFilename = getRealFilename();

        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realFilename);

            if (!fileObject.exists()) {
                if (isFailIfFileNotExists()) {
                    // File doesn't exist and fail flag is on.
                    result.setResult(false);
                    log.logError(toString(), Messages
                            .getString("JobEntryDeleteFile.ERROR_0004_File_Does_Not_Exist", realFilename)); //$NON-NLS-1$
                } else {
                    // File already deleted, no reason to try to delete it
                    result.setResult(true);
                    if (log.isBasic())
                        log.logBasic(toString(),
                                Messages.getString("JobEntryDeleteFile.File_Already_Deleted", realFilename)); //$NON-NLS-1$
                }
            } else {
                // Here gc() is explicitly called if e.g. createfile is used
                // in the same
                // job for the same file. The problem is that after creating
                // the file the
                // file object is not properly garbaged collected and thus
                // the file cannot
                // be deleted anymore. This is a known problem in the JVM.
                System.gc();

                boolean deleted = fileObject.delete();
                if (!deleted) {
                    log.logError(toString(), Messages
                            .getString("JobEntryDeleteFile.ERROR_0005_Could_Not_Delete_File", realFilename)); //$NON-NLS-1$
                    result.setResult(false);
                    result.setNrErrors(1);
                }
                if (log.isBasic())
                    log.logBasic(toString(),
                            Messages.getString("JobEntryDeleteFile.File_Deleted", realFilename)); //$NON-NLS-1$
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(), Messages.getString("JobEntryDeleteFile.ERROR_0006_Exception_Deleting_File", //$NON-NLS-1$
                    realFilename, e.getMessage()));
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        log.logError(toString(), Messages.getString("JobEntryDeleteFile.ERROR_0007_No_Filename_Is_Defined")); //$NON-NLS-1$
    }

    return result;
}

From source file:gov.nist.appvet.servlet.AppVetServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    String userName = request.getParameter("username");
    String password = request.getParameter("password");
    String sessionId = request.getParameter("sessionid");
    String commandStr = request.getParameter("command");
    String appId = request.getParameter("appid");
    String report = request.getParameter("report");
    String appName = request.getParameter("appname");
    String clientIpAddress = request.getRemoteAddr();

    try {//from w w  w  . jav  a 2  s.co  m
        //-------------------------- Authenticate --------------------------
        if (isAuthenticated(sessionId, userName, password, clientIpAddress, commandStr)) {
            if (sessionId != null) {
                userName = Database.getSessionUser(sessionId);
            }
        } else {
            sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                    ErrorMessage.AUTHENTICATION_ERROR.getDescription(), response,
                    HttpServletResponse.SC_BAD_REQUEST, true);
            return;
        }

        //------------------------- Handle command -------------------------
        final AppVetServletCommand command = AppVetServletCommand.getCommand(commandStr);
        switch (command) {

        // Used solely by third-party clients that are not app stores nor
        // analysis (tool service) providers.
        case AUTHENTICATE:
            sessionId = Database.setSession(userName, clientIpAddress);
            sendHttpResponse(userName, appId, command.name(), clientIpAddress, "SESSIONID=" + sessionId,
                    response, HttpServletResponse.SC_OK, false);
            return;
        case GET_STATUS:
            log.debug(userName + " invoked " + command.name() + " on app " + appId);
            final AppStatus currentStatus = AppStatusManager.getAppStatus(appId);
            sendHttpResponse(userName, appId, command.name(), clientIpAddress,
                    "CURRENT_STATUS=" + currentStatus.name(), response, HttpServletResponse.SC_OK, false);
            break;

        // Used by all clients.
        case GET_TOOL_REPORT:
            log.debug(userName + " invoked " + command.name() + " of " + report + " on app " + appId);
            returnReport(response, appId, report, clientIpAddress);
            break;
        case GET_APP_LOG:
            log.debug(userName + " invoked " + command.name() + " on app " + appId);
            returnAppLog(response, appId, clientIpAddress);
            break;
        case GET_APPVET_LOG:
            log.debug(userName + " invoked " + command.name());
            returnAppVetLog(response, clientIpAddress);
            break;
        case DOWNLOAD_APP:
            log.debug(userName + " invoked " + command.name() + " on app " + appId);
            downloadApp(response, appId, appName, clientIpAddress);
            break;
        case DOWNLOAD_REPORTS:
            log.debug(userName + " invoked " + command.name() + " on " + "app " + appId);
            final AppStatus appStatus = AppStatusManager.getAppStatus(appId);
            if (appStatus != null) {
                if (appStatus == AppStatus.ERROR || appStatus == AppStatus.FAIL
                        || appStatus == AppStatus.WARNING || appStatus == AppStatus.PASS) {
                    downloadReports(response, appId, sessionId, clientIpAddress);
                } else {
                    sendHttpResponse(userName, appId, command.name(), clientIpAddress,
                            "App " + appId + " has not finished processing", response,
                            HttpServletResponse.SC_BAD_REQUEST, true);
                }
            } else {
                log.warn("Null appstatus in doGet()");
            }
            break;
        default:
            log.warn("Received unknown command: " + commandStr + " from IP: " + clientIpAddress);
        }
    } finally {
        userName = null;
        password = null;
        sessionId = null;
        commandStr = null;
        appId = null;
        report = null;
        appName = null;
        clientIpAddress = null;
        System.gc();
    }
}

From source file:es.prodevelop.gvsig.mini.tasks.weather.WeatherFunctionality.java

private String parseGeoNames(final byte[] data) {

    final KXmlParser kxmlParser = new KXmlParser();
    StringBuffer s = new StringBuffer();

    try {//from   w  w w  .  j  av  a 2  s.  c o  m
        kxmlParser.setInput(new ByteArrayInputStream(data), "UTF-8");
        kxmlParser.nextTag();
        int tag;
        if (kxmlParser.getEventType() != KXmlParser.END_DOCUMENT) {
            kxmlParser.require(KXmlParser.START_TAG, null, "geonames");
            tag = kxmlParser.nextTag();
            while (tag != KXmlParser.END_DOCUMENT) {
                switch (tag) {
                case KXmlParser.START_TAG:
                    if (kxmlParser.getName().compareTo("name") == 0) {
                        final String desc = kxmlParser.nextText();
                        s.append(desc).append(",");
                    } else if (kxmlParser.getName().compareTo("countryName") == 0) {
                        final String desc = kxmlParser.nextText();
                        s.append(desc);
                    }
                    break;

                case KXmlParser.END_TAG:
                    break;
                }
                tag = kxmlParser.next();
            }
            // kxmlParser.require(KXmlParser.END_DOCUMENT, null, null);
        }
    } catch (XmlPullParserException parser_ex) {
        log.log(Level.SEVERE, "", parser_ex);
    } catch (IOException ioe) {
        log.log(Level.SEVERE, "", ioe);
    } catch (OutOfMemoryError ou) {
        System.gc();
        System.gc();
        log.log(Level.SEVERE, "", ou);
    } finally {
        return s.toString();
    }
}

From source file:dendroscope.autumn.hybridnetwork.ComputeHybridizationNetwork.java

/**
 * run the algorithm//  w ww.  j  ava 2  s. c  o m
 *
 * @param tree1
 * @param tree2
 * @param hybridizationNumber
 * @return reduced trees
 */
private TreeData[] run(TreeData tree1, TreeData tree2, int upperBound, Single<Integer> hybridizationNumber)
        throws IOException, CanceledException {
    verbose = ProgramProperties.get("verbose-HL", false);
    Taxa allTaxa = new Taxa();
    Pair<Root, Root> roots = PreProcess.apply(tree1, tree2, allTaxa);
    Root root1 = roots.getFirst();
    Root root2 = roots.getSecond();

    if (root1.getOutDegree() == 1 && root1.getFirstOutEdge().getTarget().getOutDegree() > 0) {
        Root tmp = (Root) root1.getFirstOutEdge().getTarget();
        root1.deleteNode();
        root1 = tmp;
    }

    if (root2.getOutDegree() == 1 && root2.getFirstOutEdge().getTarget().getOutDegree() > 0) {
        Root tmp = (Root) root2.getFirstOutEdge().getTarget();
        root2.deleteNode();
        root2 = tmp;
    }

    BitSet onlyTree1 = Cluster.setminus(root1.getTaxa(), root2.getTaxa());
    BitSet onlyTree2 = Cluster.setminus(root2.getTaxa(), root1.getTaxa());

    if (root1.getTaxa().cardinality() == onlyTree1.cardinality())
        throw new IOException("None of the taxa in second tree are contained in first tree");
    if (root2.getTaxa().cardinality() == onlyTree2.cardinality())
        throw new IOException("None of the taxa in first tree are contained in second tree");

    if (onlyTree1.cardinality() > 0) {
        System.err.println("Killing all taxa only present in first tree: " + onlyTree1.cardinality());
        for (int t = onlyTree1.nextSetBit(0); t != -1; t = onlyTree1.nextSetBit(t + 1)) {
            RemoveTaxon.apply(root1, 1, t);
        }
    }

    if (onlyTree2.cardinality() > 0) {
        System.err.println("Killing all taxa only present in second tree: " + onlyTree2.cardinality());
        for (int t = onlyTree2.nextSetBit(0); t != -1; t = onlyTree2.nextSetBit(t + 1)) {
            RemoveTaxon.apply(root2, 2, t);
        }
    }

    // run the refine algorithm
    System.err.println("Computing common refinement of both trees");
    Refine.apply(root1, root2);

    if (tree1.getRoot() == null || tree2.getRoot() == null) {
        throw new IOException(
                "Can't compute hybridization networks, at least one of the trees is empty or unrooted");
    }

    // we maintain both trees in lexicographic order for ease of comparison
    root1.reorderSubTree();
    root2.reorderSubTree();

    System.err.println(
            "Computing hybridization networks using Autumn algorithm (Autumn algorithm, Huson and Linz, 2016)...");
    progressListener.setTasks("Computing hybridization networks", "(Unknown how long this will really take)");
    progressListener.setMaximum(20);
    progressListener.setProgress(0);
    long startTime = System.currentTimeMillis();
    nextTime = startTime + waitTime;
    Set<Root> result = new TreeSet<>(new NetworkComparator());
    int h = computeRec(root1, root2, false, getAllAliveTaxa(root1, root2), upperBound, result, ">");

    fixOrdering(result);

    if (false) {
        Collection<Root> maafs = MAAFUtils.computeAllMAAFs(result);
        System.err.println("MAAFs before:");
        for (Root root : maafs) {
            System.err.println(root.toStringNetworkFull());
        }
    }
    int numberOfDuplicatesRemoved = MAAFUtils.removeDuplicateMAAFs(result, false);
    if (numberOfDuplicatesRemoved > 0)
        System.err.println("MAAF duplicates removed: " + numberOfDuplicatesRemoved);
    if (false) {
        Collection<Root> maafs = MAAFUtils.computeAllMAAFs(result);
        System.err.println("MAAFs after:");
        for (Root root : maafs) {
            System.err.println(root.toStringNetworkFull());
        }
    }

    fixOrdering(result);

    BitSet missingTaxa = Cluster.union(onlyTree1, onlyTree2);
    if (missingTaxa.cardinality() > 0) {
        System.err.println("Reattaching killed taxa: " + missingTaxa.cardinality());
        for (Root r : result) {
            for (int t = missingTaxa.nextSetBit(0); t != -1; t = missingTaxa.nextSetBit(t + 1)) {
                RemoveTaxon.unapply(r, t);
            }
        }
    }

    System.err.println("Hybridization number: " + h);
    hybridizationNumber.set(h);
    System.err.println("Total networks: " + result.size());
    System.err.println("Time: " + ((System.currentTimeMillis() - startTime) / 1000) + " secs");

    System.err.println(
            "(Size lookup table: " + lookupTable.size() + ", number of times used: " + numberOfLookups + ")");
    lookupTable.clear();
    System.gc();

    if (false) {
        System.err.println("Networks:");
        for (Root root : result) {
            System.err.println(root.toStringNetworkFull());
        }
    }

    System.gc();

    List<TreeData> list = PostProcess.apply(result.toArray(new Root[result.size()]), allTaxa, false);
    return list.toArray(new TreeData[list.size()]);
}

From source file:br.com.uol.runas.classloader.ClassLoaderGC.java

private void forceGC(WeakReference<?> reference) {
    final int maxAttempts = 20;

    for (int attempt = 1; attempt <= maxAttempts && isNotThreadInterrupted(); attempt++) {
        System.gc();

        if (reference.get() == null) {
            System.err.println("GCed!");
            break;
        } else if (attempt == maxAttempts) {
            System.err.println("Potential ClassLoader Leak --->" + reference.get());
        } else {/*  w  w w.  j a v  a2  s . com*/
            sleep();
        }
    }
}

From source file:com.duroty.application.files.manager.StoreManager.java

/**
 * DOCUMENT ME!/*from   w  w  w . j  a va 2s .c  om*/
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param identity DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files,
        int label, String charset) throws FilesException {
    ByteArrayInputStream bais = null;
    FileOutputStream fos = null;

    try {
        if ((files == null) || (files.size() <= 0)) {
            return;
        }

        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        Users user = getUser(hsession, repositoryName);
        Identity identity = getDefaultIdentity(hsession, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());

        for (int i = 0; i < files.size(); i++) {
            MultiPartEmail email = email = new MultiPartEmail();
            email.setCharset(charset);

            if (_from != null) {
                email.setFrom(_from.getAddress(), _from.getPersonal());
            }

            if (_returnPath != null) {
                email.addHeader("Return-Path", _returnPath.getAddress());
                email.addHeader("Errors-To", _returnPath.getAddress());
                email.addHeader("X-Errors-To", _returnPath.getAddress());
            }

            if (_replyTo != null) {
                email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
            }

            if (_to != null) {
                email.addTo(_to.getAddress(), _to.getPersonal());
            }

            MailPartObj obj = (MailPartObj) files.get(i);

            email.setSubject("Files-System " + obj.getName());

            Date now = new Date();
            email.setSentDate(now);

            File dir = new File(System.getProperty("user.home") + File.separator + "tmp");

            if (!dir.exists()) {
                dir.mkdir();
            }

            File file = new File(dir, obj.getName());

            bais = new ByteArrayInputStream(obj.getAttachent());
            fos = new FileOutputStream(file);
            IOUtils.copy(bais, fos);

            IOUtils.closeQuietly(bais);
            IOUtils.closeQuietly(fos);

            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(file.getPath());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("File Attachment: " + file.getName());
            attachment.setName(file.getName());

            email.attach(attachment);

            String mid = getId();
            email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">");
            email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">");

            email.addHeader("X-DBox", "FILES");

            email.addHeader("X-DRecent", "false");

            //email.setMsg(body);
            email.setMailSession(session);

            email.buildMimeMessage();

            MimeMessage mime = email.getMimeMessage();

            int size = MessageUtilities.getMessageSize(mime);

            if (!controlQuota(hsession, user, size)) {
                throw new MailException("ErrorMessages.mail.quota.exceded");
            }

            messageable.storeMessage(mid, mime, user);
        }
    } catch (FilesException e) {
        throw e;
    } catch (Exception e) {
        throw new FilesException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new FilesException(ex);
    } catch (Throwable e) {
        throw new FilesException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.photon.phresco.service.tools.SoftwareDownloadGenerator.java

private void uploadSoftwareFileToRepository(ArtifactGroup info) throws PhrescoException {
        if (deployArtifacts == false) {
            return;
        }/* w w w  . j  a va 2s.com*/

        String string = filePathMap.get(info.getName());
        if (StringUtils.isNotEmpty(string)) {
            File softwareFile = new File(softDir, string);
            com.photon.phresco.service.model.ArtifactInfo attifactInfo = new com.photon.phresco.service.model.ArtifactInfo(
                    info.getGroupId(), info.getArtifactId(), "", info.getPackaging(),
                    info.getVersions().get(0).getVersion());
            manager.addArtifact(attifactInfo, softwareFile, "photon");
            System.gc();
            System.gc();
            System.out.println(softwareFile.getPath() + " Uploaded Successfully..... ");
        }

    }

From source file:com.life.wuhan.util.ImageDownloader.java

private Bitmap downloadBitmap(final String imageUrl) {

    // AndroidHttpClient is not allowed to be used from the main thread
    final HttpClient client = new DefaultHttpClient();
    // ??//  w  w w .  ja  v  a2s  . c om
    if (NetworkUtil.getNetworkType(mContext) == NetworkUtil.APN_CMWAP) {
        HttpHost proxy = new HttpHost(NetworkUtil.getHostIp(), NetworkUtil.getHostPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    final HttpGet getRequest = new HttpGet(imageUrl);
    try {
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            final byte[] respBytes = EntityUtils.toByteArray(entity);
            writeImageFile(imageUrl, entity, respBytes);
            // Decode the bytes and return the bitmap.
            return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, null);

        }
    } catch (IOException e) {
        getRequest.abort();
    } catch (OutOfMemoryError e) {
        clearCache();
        System.gc();
    } catch (IllegalStateException e) {
        getRequest.abort();
    } catch (Exception e) {
        getRequest.abort();
    } finally {
    }
    return null;
}