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:dbs_project.storage.performance.StorageTest.java

private/* static */void printMemory(int scale) {
    for (int i = 0; i < 5; ++i) {
        System.gc();
    }//from  w  w w. ja v  a  2  s  .c om
    float footprint = ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024f
            / 1024f);
    scaleResults.add("<measurement><name>footprint</name>" + "<scale>" + scale + "</scale>" + "<value>"
            + footprint + "</value></measurement>");
    Utils.getOut().println("Memory footprint: " + footprint + " MB");
}

From source file:eu.planets_project.pp.plato.action.project.XmlAction.java

/**
 * Stores projects in the database.//from w ww  .ja v  a  2 s.c o m
 *  
 * @param plans
 */
private void storeProjects(List<Plan> plans) {
    /*
     * store all projects
     */
    while (!plans.isEmpty()) {
        Plan plan = plans.get(0);
        em.persist(plan);
        em.flush();

        plans.remove(plan);
        plan = null;
        em.clear();
        System.gc();
    }
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

@Override
public void onTrimMemory(int level) {
    System.gc();
    logMemory("onTrimMemory" + level);
}

From source file:ch.ethz.dcg.jukefox.commons.utils.AndroidUtils.java

public static Bitmap getBitmapFromFile(String path, int maxSize) {
    Bitmap bitmap = null;/*w w w .j a va  2s  .  com*/
    int dummySize = maxSize * maxSize / 4; // KB
    while (bitmap == null && dummySize <= maxSize * maxSize * 4) {
        try {
            int sampleFactor = getSampleFactor(path, maxSize);
            BitmapFactory.Options resample = new BitmapFactory.Options();
            resample.inSampleSize = sampleFactor;
            bitmap = BitmapFactory.decodeFile(path, resample);
        } catch (Throwable e) {
            // Avoid that heap has to be grown for the BitmapFactory,
            // as this would lead to an out of memory error
            int[] dummyArray = new int[dummySize * 1024];
            // Avoid being eliminated by optimization of compiler
            if (dummyArray != null) {
                dummyArray = null;
                System.gc();
            }
            Log.w(TAG, e);
            dummySize *= 2;
        }
    }
    return bitmap;

}

From source file:edu.harvard.i2b2.eclipse.plugins.ontology.ws.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   www . ja  v a2s  .  c  om
    //      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);
    }

    int timeout = processSecurityResult(response);
    //      log.info("get timeout from server: "+ timeout + " at: "+Calendar.getInstance().getTime());
    if (timeout != -1) {
        UserInfoBean.setLastActivityTime(Calendar.getInstance().getTime());
        UserInfoBean.getInstance().setUserPasswordTimeout(timeout);
        //log.info("get timeout from server: "+ timeout + " at: "+Calendar.getInstance().getTime());
    }
    return response;

}

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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {

    AppVetServletCommand command = null;
    String commandStr = null;// ww w.  j  av a 2s.  c o m
    String userName = null;
    String password = null;
    String sessionId = null;
    String toolId = null;
    String toolRisk = null;
    String appId = null;
    FileItem fileItem = null;
    String clientIpAddress = request.getRemoteAddr();
    FileItemFactory factory = null;
    ServletFileUpload upload = null;
    List<FileItem> items = null;
    Iterator<FileItem> iter = null;
    FileItem item = null;

    try {
        factory = new DiskFileItemFactory();
        upload = new ServletFileUpload(factory);
        items = upload.parseRequest(request);
        iter = items.iterator();
        String incomingParameter = null;
        String incomingValue = null;
        while (iter.hasNext()) {
            item = iter.next();
            if (item.isFormField()) {
                incomingParameter = item.getFieldName();
                incomingValue = item.getString();
                if (incomingParameter.equals("command")) {
                    commandStr = incomingValue;
                    log.debug("commandStr: " + commandStr);
                } else if (incomingParameter.equals("username")) {
                    userName = incomingValue;
                    log.debug("userName: " + userName);
                } else if (incomingParameter.equals("password")) {
                    password = incomingValue;
                    log.debug("password: " + password);
                } else if (incomingParameter.equals("sessionid")) {
                    sessionId = incomingValue;
                    log.debug("sessionId: " + sessionId);
                } else if (incomingParameter.equals("toolid")) {
                    toolId = incomingValue;
                    log.debug("toolid: " + toolId);
                } else if (incomingParameter.equals("toolrisk")) {
                    toolRisk = incomingValue;
                    log.debug("toolrisk: " + toolRisk);
                } else if (incomingParameter.equals("appid")) {
                    appId = incomingValue;
                    log.debug("appId: " + appId);
                } else {
                    log.warn("Received unknown parameter: " + incomingValue + " from IP: " + clientIpAddress);
                }
            } else {
                // item should now hold the received file
                fileItem = item;
            }
        }
        incomingParameter = null;
        incomingValue = null;

        //-------------------------- 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;
        }

        //--------------------- Verify file attachment ---------------------
        if (fileItem == null) {
            sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                    ErrorMessage.MISSING_FILE.getDescription(), response, HttpServletResponse.SC_BAD_REQUEST,
                    true);
            return;
        }
        if (!ValidateBase.isLegalFileName(fileItem.getName())) {
            sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                    ErrorMessage.ILLEGAL_CHAR_IN_UPLOADED_FILENAME_ERROR.getDescription(), response,
                    HttpServletResponse.SC_BAD_REQUEST, true);
            return;
        }

        //------------------------- Handle command -------------------------
        AppInfo appInfo = null;
        command = AppVetServletCommand.valueOf(commandStr);
        switch (command) {
        case SUBMIT_APP:
            log.debug(userName + " invoked " + command.name() + " with file " + fileItem.getName());
            if (!ValidateBase.hasValidAppFileExtension(fileItem.getName())) {
                sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                        ErrorMessage.INVALID_APP_FILE_EXTENSION.getDescription(), response,
                        HttpServletResponse.SC_BAD_REQUEST, true);
                return;
            } else {
                appInfo = createAppInfo(userName, sessionId, fileItem, clientIpAddress, request);
                if (appInfo == null)
                    return;
                else {
                    sendHttpResponse(userName, appInfo.appId, commandStr, clientIpAddress,
                            "HTTP/1.1 202 Accepted", response, HttpServletResponse.SC_ACCEPTED, false);
                    Registration registration = new Registration(appInfo);
                    registration.registerApp();
                }
            }
            break;
        case SUBMIT_REPORT:
            log.debug(userName + " invoked " + command.name() + " on app " + appId + " with report "
                    + fileItem.getName());
            if (!ValidateBase.hasValidReportFileExtension(fileItem.getName())) {
                sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                        ErrorMessage.INVALID_REPORT_FILE_EXTENSION.getDescription(), response,
                        HttpServletResponse.SC_BAD_REQUEST, true);
                return;
            } else {
                sendHttpResponse(userName, appId, commandStr, clientIpAddress, "HTTP/1.1 202 Accepted",
                        response, HttpServletResponse.SC_ACCEPTED, false);
                appInfo = createAppInfo(appId, userName, commandStr, toolId, toolRisk, fileItem,
                        clientIpAddress, response);
                if (appInfo == null)
                    return;
                else
                    submitReport(userName, appInfo, response);
            }
            break;
        default:
            log.warn("Received unknown command: " + commandStr + " from IP: " + clientIpAddress);
        }
    } catch (final FileUploadException e) {
        sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                ErrorMessage.FILE_UPLOAD_ERROR.getDescription(), response, HttpServletResponse.SC_BAD_REQUEST,
                true);
        return;
    } finally {
        command = null;
        commandStr = null;
        userName = null;
        password = null;
        sessionId = null;
        toolId = null;
        toolRisk = null;
        appId = null;
        fileItem = null;
        clientIpAddress = null;
        factory = null;
        upload = null;
        items = null;
        iter = null;
        item = null;
        System.gc();
    }
}

From source file:datascript.instance.DataScriptInstanceTool.java

private void parseInstance() throws Exception {
    //FileBitStreamReader reader = new FileBitStreamReader(instanceFileName);
    LineCreator lineCreator = new LineCreator();
    byte[] blob = lineCreator.getLines(10000, 5);
    for (int i = 0; i < 100; i++) {
        System.gc();
        ByteArrayBitStreamReader reader = new ByteArrayBitStreamReader(blob);
        AstDataScriptInstanceParser parser = new AstDataScriptInstanceParser(reader);
        LineGeometriesInstanceHandler handler = new LineGeometriesInstanceHandler();
        parser.setInstanceHandler(handler);
        //parser.setInstanceHandler(new EchoingInstanceHandler());
        long start = System.currentTimeMillis();
        parser.parse(typeName);//from   ww w .  j a v  a2  s.c o  m
        long stop = System.currentTimeMillis();
        System.out.println(
                "Building application structure from instance parser events: " + (stop - start) + " ms");
        reader.setBitPosition(0);

        ByteArrayBitStreamReader reader2 = new ByteArrayBitStreamReader(blob);
        start = System.currentTimeMillis();
        LineGeometries geometries = new LineGeometries(reader2);
        stop = System.currentTimeMillis();
        System.out.println("Building DataScript object tree: " + (stop - start) + " ms");

        start = System.currentTimeMillis();
        handler.decode(geometries);
        stop = System.currentTimeMillis();
        System.out.println("Building application structure from object tree: " + (stop - start) + " ms");

        start = System.currentTimeMillis();
        handler.decodeManually(blob);
        stop = System.currentTimeMillis();
        System.out.println("Building application structure by manual decoding: " + (stop - start) + " ms");
        System.out.println();
    }
}

From source file:com.phonegap.PhoneGap.java

/**
 * Processes a new HttpConnection object to instantiate a new browser Field (aka WebView) object, and then resets the screen to the newly-created Field.
 * @param connection/*from  w  w  w  .j  a  va 2  s .c  om*/
 * @param e
 */
public void processConnection(HttpConnection connection, Event e) {
    // Cancel previous request.
    if (_currentConnection != null) {
        try {
            _currentConnection.close();
        } catch (IOException e1) {
        }
    }
    // Clear out pending responses.
    synchronized (pendingResponses) {
        pendingResponses.removeAllElements();
    }
    // Cancel any XHRs happening.
    commandManager.stopXHR();
    _currentConnection = connection;
    BrowserContent browserContent = null;
    Field field = null;
    try {
        browserContent = _renderingSession.getBrowserContent(connection, this, e);
        if (browserContent != null) {
            field = browserContent.getDisplayableContent();
            if (field != null) {
                synchronized (Application.getEventLock()) {
                    // The deleteAll call will remove the loading screen if exists.
                    _mainScreen.deleteAll();
                    _mainScreen.add(field);
                }
            }
            browserContent.finishLoading();
        }
    } catch (RenderingException re) {
    } finally {
        browserContent = null;
        field = null;
        this.hideLoadingScreen();
        // Manually call the garbage collector to clean up all of leftover objects and free up the nulled object handles.
        System.gc();
    }
}

From source file:com.app.server.EARDeployer.java

/**
 * This method removes the executor services from the executor services
 * map.//from ww  w .  j ava  2  s .  c o m
 * 
 * @param jarFile
 * @param classList
 * @throws FileSystemException
 */
public void deleteExecutorServicesEar(URL url) throws FileSystemException {
    try {
        File file = new File(url.toURI());
        String fileName = file.getName();
        synchronized (urlClassLoaderMap) {
            ConcurrentHashMap map = (ConcurrentHashMap) filesMap.get(fileName);
            if (map != null) {
                //log.info("ClassLoader Map=\n\n\n\n"+urlClassLoaderMap);
                Set keysinclassloadermap = map.keySet();
                log.info(keysinclassloadermap.size());
                Iterator classloaders = keysinclassloadermap.iterator();
                while (classloaders.hasNext()) {
                    String classloader = (String) classloaders.next();
                    log.info("ClassLoader=" + classloader);
                    ClassLoader webClassLoader = (ClassLoader) this.urlClassLoaderMap.get(map.get(classloader));
                    this.urlClassLoaderMap.remove(map.get(classloader));
                    ClassLoaderUtil.cleanupJarFileFactory(ClassLoaderUtil.closeClassLoader(webClassLoader));
                    urlClassLoaderMap.remove(map.get(classloader));
                    try {
                        if (webClassLoader instanceof WebClassLoader)
                            ((WebClassLoader) webClassLoader).close();
                        else if (webClassLoader instanceof VFSClassLoader) {
                            FileObject[] fObj = ((VFSClassLoader) webClassLoader).getFileObjects();
                            for (FileObject obj : fObj) {
                                obj.close();
                            }
                        }
                    } catch (Throwable e) {
                        log.error("Error in closing the classLoader", e);
                        // TODO Auto-generated catch block
                        //e.printStackTrace();
                    }
                    /*if (classloader.contains(deployDirectory +"/"+ fileName)) {
                       log.info("removing classloader" + deployDirectory
                      + classloader);
                          File warDir=new File(fileName);
                          if(warDir.exists()){                                    
                      warDeployer.deleteDir(warDir);
                          }
                          //log.info("Before Remove class loader\n\n\n\n"+this.urlClassLoaderMap);                           
                          //log.info("Remove class loader\n\n\n\n"+this.urlClassLoaderMap);
                    }*/
                }
                System.gc();
                classloaders = keysinclassloadermap.iterator();
                while (classloaders.hasNext()) {
                    String classloader = (String) classloaders.next();
                    if (classloader.endsWith(".war")) {
                        mbeanServer.invoke(warObjectName, "removeServlets",
                                new Object[] { (String) map.get(classloader), classloader },
                                new String[] { String.class.getName(), String.class.getName() });
                        File warDir = new File((String) map.get(classloader));
                        if (warDir.exists()) {
                            deleteDir(warDir);
                        }
                    }
                }
                log.info(this.urlClassLoaderMap);
            }
            filesMap.remove(fileName);
        }
    } catch (Exception ex) {
        try {
            log.error("Error in removing the executor services configuration for the file name "
                    + url.toURI().toString(), ex);
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //ex.printStackTrace();
    }
}

From source file:edu.harvard.mcz.imagecapture.ui.ButtonEditor.java

@Override
public void actionPerformed(ActionEvent e) {

    // Action might not be event_button_pressed on all systems.
    log.debug("Button event actionCommand: " + e.getActionCommand());
    if (e.getActionCommand().equals(EVENT_PRESSED)) {
        // Event is a click on the cell
        // Identify the row that was clicked on.
        JTable table = (JTable) ((JButton) e.getSource()).getParent();
        log.debug(e.getSource());/*from  w  w  w. j  a v  a2 s.  c  o m*/
        log.debug(table);
        int row = table.getEditingRow();
        // Stop editing - note, we need to have gotten e.getSource.getParent and getEditingRow first.
        fireEditingStopped(); //Make the renderer reappear.
        Singleton.getSingletonInstance().getMainFrame()
                .setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        switch (formToOpen) {
        case OPEN_SPECIMEN_DETAILS:
            // Load the selected specimen record from its ID (the data value behind the button).
            //SpecimenLifeCycle sls = new SpecimenLifeCycle();
            //Specimen specimen = sls.findById((Long)targetId);
            //if (specimen!=null) {
            if (targetId != null) {
                // a specimen with this ID exists, bring up the details editor.
                try {
                    //SpecimenControler sc = new SpecimenControler(specimen);
                    if (((Specimen) targetId).getSpecimenId() != null) {
                        if (((Specimen) targetId).isStateDone()) {
                            // Specimens in state_done are no longer editable
                            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                    "This Specimen record has been migrated and can no longer be edited here ["
                                            + ((Specimen) targetId).getLoadFlags()
                                            + "].\nSee: http://mczbase.mcz.harvard.edu/guid/MCZ:Ent:"
                                            + ((Specimen) targetId).getCatNum(),
                                    "Migrated Specimen", JOptionPane.WARNING_MESSAGE);
                        } else {
                            // Specimen is still editable
                            if (table != null) {
                                // Pass the specimen object for the row, the table model, and the row number on to the specimen controler.
                                try {
                                    SpecimenControler sc = new SpecimenControler((Specimen) targetId,
                                            (SpecimenListTableModel) table.getModel(), table, row);
                                    if (table.getParent().getParent().getParent().getParent()
                                            .getClass() == SpecimenBrowser.class) {
                                        sc.addListener((DataChangeListener) table.getParent());
                                    } else {
                                        Component x = table;
                                        boolean done = false;
                                        while (!done) {
                                            log.debug(x.getParent());
                                            x = x.getParent();
                                            if (x.getClass() == SpecimenBrowser.class) {
                                                sc.addListener((DataChangeListener) x);
                                                done = true;
                                            }
                                        }
                                    }
                                    sc.displayInEditor();
                                } catch (java.lang.ClassCastException eNotSp) {
                                    // Request isn't coming from a SpecimenListTableModel
                                    // View just the specimen record.
                                    SpecimenControler sc = new SpecimenControler((Specimen) targetId);
                                    sc.displayInEditor();
                                }
                            } else {
                                log.debug(e.getSource());
                                //SpecimenControler sc = new SpecimenControler((Specimen)targetId);
                                //sc.displayInEditor();
                            }
                        }
                    } else {
                        log.debug("User clicked on table row containing a new Specimen()");
                        JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                "No Specimen for this image", "Load Specimen Failed",
                                JOptionPane.WARNING_MESSAGE);
                    }
                } catch (NoSuchRecordException e1) {
                    log.error("Tested for specimen!=null, but SpecimenControler threw null specimen exception");
                    log.error(e1);
                }
            } else {
                log.debug("No matches found to specimen id=" + targetId);
                // TODO: Create new specimen record and bring up dialog
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "No specimen record.");
            }
            break;
        case OPEN_TEMPLATE:
            // Load the selected specimen record from its ID (the data value behind the button).
            try {
                // a template with this targetID exists, display it.
                ((PositionTemplateEditor) parentComponent).setTemplate((String) targetId);
            } catch (NoSuchTemplateException e1) {
                log.error("No such template on button press on a template in list.");
                log.error(e1);
                log.trace(e1);
            }

            break;
        case OPEN_USER:
            //TODO: tie to user
            log.debug("Open user");
            ((UserListBrowser) parentComponent).getEditUserPanel().setUser((Users) targetId);
            break;
        case OPEN_SPECIMEN_VERBATIM:
            log.debug("Open Verbatim Transcription");
            SpecimenLifeCycle sls = new SpecimenLifeCycle();
            List<Specimen> toTranscribe = sls.findForVerbatim(((GenusSpeciesCount) targetId).getGenus(),
                    ((GenusSpeciesCount) targetId).getSpecificEpithet(), WorkFlowStatus.STAGE_1);
            log.debug(toTranscribe.size());
            SpecimenListTableModel stm = new SpecimenListTableModel(toTranscribe);
            JTable stable = new JTable();
            stable.setModel(stm);
            SpecimenControler verbCont;
            try {
                verbCont = new SpecimenControler(toTranscribe.get(0), stm, stable, 0);
                VerbatimCaptureDialog dialog = new VerbatimCaptureDialog(toTranscribe.get(0), verbCont);
                dialog.setVisible(true);
            } catch (NoSuchRecordException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            break;
        case OPEN_VERBATIM_CLASSIFY:
            log.debug("Open Verbatim Classify dialog");
            try {
                VerbatimClassifyDialog dialog = new VerbatimClassifyDialog(
                        (VerbatimCount) table.getModel().getValueAt(row, 0));
                dialog.setVisible(true);
            } catch (ClassCastException e1) {
                log.error(e1.getMessage(), e1);
            }
            break;
        case ACTION_CANCEL_JOB:
            log.debug("Action Cancel requested on job " + targetId);
            Singleton.getSingletonInstance().getJobList().getJobAt((Integer) targetId).cancel();
            break;
        case OPEN_SPECIMENPARTATTRIBUTES:
            SpecimenPartAttributeDialog attrDialog = new SpecimenPartAttributeDialog((SpecimenPart) targetId);
            attrDialog.setVisible(true);
            break;
        }
        Singleton.getSingletonInstance().getMainFrame()
                .setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        System.gc();
    }
}