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:edu.harvard.i2b2.eclipse.plugins.query.ontologyMessaging.OntServiceDriver.java

public static String sendREST(EndpointReference restEPR, String requestString, String type) throws Exception {
    if (UserInfoBean.getInstance().getCellDataUrl("ont") == null)
        throw new I2B2Exception("Ontology cell (ONT) not configured in PM");

    OMElement getOnt = getOntPayLoad(requestString);

    if (type != null) {
        if (type.equals("ONT"))
            MessageUtil.getInstance().setNavRequest("URL: " + restEPR, getOnt.toString());
        else if (type.equals("EDIT"))
            MessageUtil.getInstance().setEditRequest("URL: " + restEPR, getOnt.toString());
        else//from  w  w w.j a  v  a 2s. c om
            MessageUtil.getInstance().setFindRequest("URL: " + restEPR, getOnt.toString());
    }
    Options options = new Options();
    log.debug(restEPR.toString());
    options.setTo(restEPR);
    options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
    options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE);
    options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(125000));
    options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, new Integer(125000));
    ServiceClient sender = OntServiceClient.getServiceClient();
    sender.setOptions(options);
    OMElement result;
    try {
        result = sender.sendReceive(getOnt);
    } catch (java.lang.OutOfMemoryError e) {
        System.gc();
        throw new I2B2Exception("Out of memory");
    }
    String response = result.toString();

    if (type != null) {
        if (type.equals("ONT"))
            MessageUtil.getInstance().setNavResponse("URL: " + restEPR, response);
        else if (type.equals("EDIT"))
            MessageUtil.getInstance().setEditResponse("URL: " + restEPR, response);
        else
            MessageUtil.getInstance().setFindResponse("URL: " + restEPR, response);
    }
    return response;
}

From source file:com.panet.imeta.job.entries.deletefolders.JobEntryDeleteFolders.java

private boolean deleteFolder(String foldername) {
    LogWriter log = LogWriter.getInstance();

    boolean rcode = false;
    FileObject filefolder = null;

    try {/*from w  ww  .  j  ava  2 s  .c  om*/
        filefolder = KettleVFS.getFileObject(foldername);

        // 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();

        if (filefolder.exists()) {
            // the file or folder exists
            if (filefolder.getType() == FileType.FOLDER) {
                // It's a folder
                if (log.isDetailed())
                    log.logDetailed(toString(),
                            Messages.getString("JobEntryDeleteFolders.ProcessingFolder", foldername)); //$NON-NLS-1$
                // Delete Files
                int Nr = filefolder.delete(new TextFileSelector());

                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString("JobEntryDeleteFolders.TotalDeleted", //$NON-NLS-1$
                            foldername, String.valueOf(Nr)));
                rcode = true;
            } else {
                // Error...This file is not a folder!
                log.logError(toString(), Messages.getString("JobEntryDeleteFolders.Error.NotFolder"));
            }
        } else {
            // File already deleted, no reason to try to delete it
            if (log.isBasic())
                log.logBasic(toString(),
                        Messages.getString("JobEntryDeleteFolders.FolderAlreadyDeleted", foldername)); //$NON-NLS-1$
            rcode = true;
        }
    } catch (IOException e) {
        log.logError(toString(),
                Messages.getString("JobEntryDeleteFolders.CouldNotDelete", foldername, e.getMessage())); //$NON-NLS-1$
    } finally {
        if (filefolder != null) {
            try {
                filefolder.close();
            } catch (IOException ex) {
            }
            ;
        }
    }

    return rcode;
}

From source file:com.alvermont.javascript.tools.shell.ShellMain.java

/**
 * Evaluate JavaScript source.//from   www  .  j  a v  a2s  .co  m
 *
 * @param cx the current context
 * @param filename the name of the file to compile, or null
 *                 for interactive mode.
 */
public static void processSource(Context cx, String filename) {
    if (filename == null || filename.equals("-")) {
        final PrintStream ps = GLOBAL.getErr();

        if (filename == null) {
            // print implementation version
            ps.println(cx.getImplementationVersion());
        }

        // Use the interpreter for interactive input
        cx.setOptimizationLevel(-1);

        final BufferedReader in = new BufferedReader(new InputStreamReader(GLOBAL.getIn()));

        int lineno = 1;
        boolean hitEOF = false;

        while (!hitEOF) {
            final int startline = lineno;

            if (filename == null) {
                ps.print("js> ");
            }

            ps.flush();

            String source = "";

            // Collect lines of source to compile.
            while (true) {
                String newline;

                try {
                    newline = in.readLine();
                } catch (IOException ioe) {
                    ps.println(ioe.toString());

                    break;
                }

                if (newline == null) {
                    hitEOF = true;

                    break;
                }

                source = source + newline + "\n";
                ++lineno;

                if (cx.stringIsCompilableUnit(source)) {
                    break;
                }
            }

            final Script script = loadScriptFromSource(cx, source, "<stdin>", lineno, null);

            if (script != null) {
                final Object result = evaluateScript(script, cx, GLOBAL);

                if (result != Context.getUndefinedValue()) {
                    try {
                        ps.println(Context.toString(result));
                    } catch (RhinoException rex) {
                        ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                    }
                }

                final NativeArray h = GLOBAL.getHistory();
                h.put((int) h.getLength(), h, source);
            }
        }

        ps.println();
    } else {
        processFile(cx, GLOBAL, filename);
    }

    System.gc();
}

From source file:com.emc.ecs.sync.CasMigrationTest.java

protected void run(EcsSync sync) {
    System.gc();
    long startSize = Runtime.getRuntime().totalMemory();
    sync.run();/*  w w  w  .ja v a  2  s. c om*/
    System.gc();
    long endSize = Runtime.getRuntime().totalMemory();
    System.out.println(String.format("memory before sync: %d, after sync: %d", startSize, endSize));
    System.out.println(sync.getStatsString());
}

From source file:com.quix.aia.cn.imo.rest.AddressBookRest.java

/**
 * <p>//from   www .j a va2 s .co  m
 * This method inserts Candidate Note record.
 * </p>
 */
//[{"addressCode":172926,"iosAddressCode":"38","activityType":"Participation","activityDate":"2015-06-06 08:00:00","description":"description","activityStatus":true}]
@POST
@Path("/syncNotes")
@Consumes(MediaType.TEXT_PLAIN)
@Produces({ MediaType.APPLICATION_JSON })
public Response syncNotes(@Context HttpServletRequest request, @Context ServletContext context,
        String jsonString) {
    log.log(Level.INFO, "Address Book --> syncNotes ");
    log.log(Level.INFO, "Address Book --> syncNotes --> Data for Sync Notes...  ::::: " + jsonString);
    String responseString = "[{\"status\":";
    MsgBeans beans = new MsgBeans();
    AuditTrailMaintenance auditTrailMaint = new AuditTrailMaintenance();
    Gson googleJson = null;
    GsonBuilder builder = new GsonBuilder();
    //        CandidateNoteId candidateNoteId = new CandidateNoteId();
    CandidateNote candidateNote = null;

    CandidateNoteMaintenance candidateNoteMaint = new CandidateNoteMaintenance();
    try {
        log.log(Level.INFO, "Address Book --> Saving Candidate Notes ... ");

        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                Date date = LMSUtil.convertDateToyyyymmddhhmmssDashed(json.getAsString());
                if (null != date) {
                    return date;
                } else {
                    return LMSUtil.convertDateToyyyy_mm_dd(json.getAsString());
                }
            }
        });

        googleJson = builder.create();
        Type listType = new TypeToken<List<CandidateNote>>() {
        }.getType();
        List<CandidateNote> jsonObjList = googleJson.fromJson(jsonString, listType);
        //           candidateNote = jsonObjList.get(0);  
        //           candidateNoteId.setAddressCode(candidateNote.getAddressCode());
        //           candidateNoteId.setIosNoteCode(candidateNote.getIosNoteCode());
        //           candidateNote.setNoteId(candidateNoteId);

        candidateNoteMaint.syncNotes(jsonObjList, request);

        //           String msg = candidateNoteMaint.createNewCandidateNote(candidateNote,request);

        log.log(Level.INFO, "Address Book --> Candidate Notes Saved successfully... ");
        responseString += true;
    } catch (Exception e) {
        e.printStackTrace();
        beans.setCode("500");
        beans.setMassage(
                "Something wrong happens, please contact administrator. Error Message : " + e.getMessage());
        auditTrailMaint.insertAuditTrail(
                new AuditTrail("Rest", AuditTrail.MODULE_ADDRESS_BOOK, AuditTrail.FUNCTION_FAIL, "FAILED"));

        log.log(Level.SEVERE, "Address Book --> Error in Saving Candidate Notes.");
        log.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        LogsMaintenance logsMain = new LogsMaintenance();
        logsMain.insertLogs("AddressBookRest", Level.SEVERE + "", errors.toString());

        responseString += false;
    } finally {
        builder = null;
        googleJson = null;
        //         candidateNoteId=null;
        auditTrailMaint = null;
        candidateNoteMaint = null;
        candidateNote = null;
        beans = null;
        System.gc();
    }

    responseString += "}]";
    return Response.status(200).entity(responseString).build();
}

From source file:com.wishlist.Wishlist.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    /*//from   w ww.j a v  a  2s .c o m
     * if this is the activity result from authorization flow, do a call back to authorizeCallback
     * Source Tag: login_tag
     */
    case AUTHORIZE_ACTIVITY_RESULT_CODE: {
        Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
        break;
    }
    /*
     * if this is the result for a photo picker from the gallery, upload the image after scaling it.
     * You can use the Utility.scaleImage() function for scaling
     */
    case PICK_EXISTING_PHOTO_RESULT_CODE: {
        if (resultCode == Activity.RESULT_OK) {
            Uri imageUri = data.getData();
            ((BitmapDrawable) image.getDrawable()).getBitmap().recycle();
            System.gc();
            try {
                imageBytes = Utility.scaleImage(getApplicationContext(), imageUri);
                image.setImageBitmap(BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length));
                image.invalidate();
            } catch (IOException e) {
                showToast(getString(R.string.error_getting_image));
            }
        } else {
            showToast(getString(R.string.no_image_selected));
        }
        break;
    }
    }
}

From source file:com.aoeng.degu.utils.net.asyncthhpclient.AsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null/*from w w  w.  j av  a  2  s  .c o m*/
 * @return response entity body or null
 * @throws java.io.IOException if reading entity or creating byte array failed
 */
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");
            }
            int buffersize = (contentLength < 0) ? BUFFER_SIZE : (int) contentLength;
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) buffersize);
                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;
}

From source file:org.b3mn.poem.Representation.java

public static void extractJsonFromDatabase(String serverUrl) throws IOException {
    ScrollableResults contents = Persistance.getSession().createSQLQuery("SELECT content.erdf FROM content")
            .setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);

    int count = 0;
    while (contents.next()) {
        String content = (String) contents.get(0);
        Writer writer = new FileWriter(
                "C:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/json/" + count + ".json");

        if (isJson(content)) {

        } else {/*from   ww  w.  j a v  a 2 s .c o  m*/
            content = erdfToJson(content, serverUrl);

        }
        if (content == null || content.indexOf("BPMNDiagram") == -1)
            continue;
        String[] labels = new String[] { "name", "documentation", "title", "description", "pooldocumentation",
                "conditionexpression", "text", "state" };
        for (String prop : labels)
            content = content.replaceAll("\"" + prop + "\":\"([\\w\\W^\"]*?(\\\\\")?[\\w\\W^\"]*?)*?\"",
                    "\"" + prop + "\":\"\"");

        FileCopyUtils.copy(content, writer);
        writer.close();

        if (++count % 10 == 0) {
            //flush a batch of updates and release memory:
            Persistance.getSession().flush();
            Persistance.getSession().clear();
        }
        System.gc();
    }
    Persistance.commit();

}

From source file:edu.harvard.i2b2.eclipse.plugins.explorer.ontologyMessaging.OntServiceDriver.java

public static String sendREST(EndpointReference restEPR, String requestString, String type) throws Exception {
    if (UserInfoBean.getInstance().getCellDataUrl("ont") == null) {
        throw new I2B2Exception("Ontology cell (ONT) not configured in PM");
    }/*from  ww w. j  ava2  s. c o m*/
    //      requestString.replaceAll("\\p{Cntrl}", "");  did not fix illegal control char error
    OMElement getOnt = getOntPayLoad(requestString);

    if (type != null) {
        if (type.equals("ONT"))
            MessageUtil.getInstance().setNavRequest("URL: " + restEPR + "\n" + getOnt.toString());
        else if (type.equals("EDIT"))
            MessageUtil.getInstance().setEditRequest("URL: " + restEPR + "\n" + getOnt.toString());
        else
            MessageUtil.getInstance().setFindRequest("URL: " + restEPR + "\n" + getOnt.toString());
    }

    Options options = new Options();
    log.debug(restEPR.toString());
    options.setTo(restEPR);
    options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

    options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE);
    options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(125000));
    options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, new Integer(125000));

    ServiceClient sender = OntServiceClient.getServiceClient();
    sender.setOptions(options);

    OMElement result;
    try {
        result = sender.sendReceive(getOnt);
    } catch (java.lang.OutOfMemoryError e) {
        System.gc();
        throw new I2B2Exception("Out of memory");
        //         return null;
    }
    String response = result.toString();

    if (type != null) {
        if (type.equals("ONT"))
            MessageUtil.getInstance().setNavResponse("URL: " + restEPR + "\n" + response);
        else if (type.equals("EDIT"))
            MessageUtil.getInstance().setEditResponse("URL: " + restEPR + "\n" + response);

        else
            MessageUtil.getInstance().setFindResponse("URL: " + restEPR + "\n" + response);
    }

    return response;

}

From source file:com.appeligo.captions.CaptionListener.java

private synchronized static void checkStats() {
    int interval = 5; // minutes
    long timestamp = new Date().getTime();
    if ((timestamp - lastWrite) > (interval * 60 * 1000)) {
        lastWrite = timestamp;/*from w ww.  j  a v  a 2 s .c  o  m*/
        String day = Utils.getDatePath(timestamp);
        if (!day.equals(currentDay)) {
            if (statsFile != null) {
                statsFile.println("</table></body></html>");
                statsFile.close();
                statsFile = null;
            }
            currentDay = day;
        }
        if (hostname == null) {
            try {
                hostname = InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                hostname = "UnknownHost";
            }
        }
        String dirname = documentRoot + "/stats/" + currentDay + "/" + hostname;
        String statsFileName = dirname + "/searchprocstats.html";
        try {
            if (statsFile == null) {
                File dir = new File(dirname);
                if ((!dir.exists()) && (!dir.mkdirs())) {
                    throw new IOException("Error creating directory " + dirname);
                }
                File file = new File(statsFileName);
                if (file.exists()) {
                    statsFile = new PrintStream(new FileOutputStream(statsFileName, true));
                    statsFile.println("<tr><td colspan='5'>Restart</td></tr>");
                } else {
                    statsFile = new PrintStream(new FileOutputStream(statsFileName));
                    String title = "Search Process (tomcat) status for " + currentDay;
                    statsFile.println("<html><head><title>" + title + "</title></head>");
                    statsFile.println("<body><h1>" + title + "</h1>");
                    statsFile.println("<table border='1'>");
                    statsFile.println("<tr>");
                    statsFile.println("<th colspan='2'>" + interval + " Minute Intervals</th>"
                            + "<th colspan='3'>Mem Pre GC</th>" + "<th>GC</th>"
                            + "<th colspan='3'>Mem Post GC</th>");
                    statsFile.println("</tr>");
                    statsFile.println("<tr>");
                    statsFile.println("<th>Timestamp</th>");
                    statsFile.println("<th>Time</th>");
                    statsFile.println("<th>Used</th>");
                    statsFile.println("<th>Committed</th>");
                    statsFile.println("<th>Max</th>");
                    statsFile.println("<th>Millis</th>");
                    statsFile.println("<th>Used</th>");
                    statsFile.println("<th>Committed</th>");
                    statsFile.println("<th>Max</th>");
                    statsFile.println("</tr>");
                }
            }
            Calendar cal = Calendar.getInstance();
            cal.setTimeZone(TimeZone.getTimeZone("GMT"));
            cal.setTimeInMillis(timestamp);
            String time = String.format("%1$tH:%1$tM:%1$tS", cal);
            MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
            MemoryUsage memory = memoryBean.getHeapMemoryUsage();
            statsFile.print("<tr>");
            statsFile.print("<td>" + timestamp + "</td>");
            statsFile.print("<td>" + time + "</td>");
            statsFile.format("<td>%,d</td>", memory.getUsed());
            statsFile.format("<td>%,d</td>", memory.getCommitted());
            statsFile.format("<td>%,d</td>", memory.getMax());
            long beforeGC = System.currentTimeMillis();
            System.gc();
            long elapsed = System.currentTimeMillis() - beforeGC;
            statsFile.format("<td>%,d</td>", (int) elapsed);
            memoryBean = ManagementFactory.getMemoryMXBean();
            memory = memoryBean.getHeapMemoryUsage();
            statsFile.format("<td>%,d</td>", memory.getUsed());
            statsFile.format("<td>%,d</td>", memory.getCommitted());
            statsFile.format("<td>%,d</td>", memory.getMax());
            statsFile.println("</tr>");
        } catch (IOException e) {
            log.error("Error opening or writing to " + statsFileName, e);
        }
    }
}