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:elaborate.editor.model.orm.service.ProjectService.java

void logMemory() {
    int mb = 1024 * 1024;
    System.gc();
    // Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();
    Log.info("##### Heap utilization statistics [MB] #####");

    // Print used memory
    Log.info("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

    // Print free memory
    Log.info("Free Memory:" + runtime.freeMemory() / mb);

    // Print total available memory
    Log.info("Total Memory:" + runtime.totalMemory() / mb);

    // Print Maximum available memory
    Log.info("Max Memory:" + runtime.maxMemory() / mb);
}

From source file:henplus.HenPlus.java

/**
 * called at the very end; on signal or called from the shutdown-hook
 *//*w  w  w  .ja va 2  s  .  c o  m*/
private void shutdown() {
    if (_alreadyShutDown) {
        return;
    }
    Logger.info("storing settings..");
    /*
     * allow hard resetting.
     */
    SigIntHandler.getInstance().reset();
    try {
        if (_dispatcher != null) {
            _dispatcher.shutdown();
        }
        if (_historyConfig != null) {
            _historyConfig.write(new ConfigurationContainer.WriteAction() {

                @Override
                public void writeConfiguration(final OutputStream out) throws Exception {
                    HistoryWriter.writeReadlineHistory(out);
                }
            });
        }
        Readline.cleanup();
    } finally {
        _alreadyShutDown = true;
    }
    /*
     * some JDBC-Drivers (notably hsqldb) do some important cleanup (closing
     * open threads, for instance) in finalizers. Force them to do their
     * duty:
     */
    System.gc();
    System.gc();
}

From source file:com.clough.android.adbv.view.MainFrame.java

private void showDeviceDisconnectedDialog() {
    JOptionPane.showMessageDialog(null, "Device " + deviceName + " is beign disconnected", "Connectio error",
            JOptionPane.ERROR_MESSAGE);
    System.exit(0);//w  ww  .ja  va2s .c  o  m
    System.gc();
}

From source file:cn.com.loopj.android.http.AsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null/*  ww w .  j av  a 2s  . co m*/
 * @return response entity body or null
 * @throws 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(buffersize);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    long count = 0;
                    int l;
                    // 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, (contentLength <= 0 ? 1 : contentLength));
                    }
                } finally {
                    AsyncHttpClient.silentCloseInputStream(instream);
                    AsyncHttpClient.endEntityViaReflection(entity);
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

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

public String exportLibrary() {
    LibraryTree lib = null;//  www .j  a  v  a  2 s.  c o  m
    List<LibraryTree> trees = null;
    trees = em.createQuery("select l from LibraryTree l where (l.name = 'mainlibrary') ").getResultList();
    if ((trees != null) && (trees.size() > 0)) {
        lib = trees.get(0);
    }

    if (lib != null) {
        // convert project-name to a filename, add date:
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_kkmmss");
        String filename = "RequirementsLibrary-" + formatter.format(new Date());

        String binarydataTempPath = OS.getTmpPath() + "RequirementsLibrary-" + System.currentTimeMillis() + "/";
        File binarydataTempDir = new File(binarydataTempPath);
        binarydataTempDir.mkdirs();

        LibraryExport exp = new LibraryExport();
        try {
            HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
                    .getExternalContext().getResponse();
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachement; filename=\"" + filename + ".xml\"");
            // the length of the resulting XML file is unknown due to formatting: response.setContentLength(xml.length());
            try {
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());

                exp.exportToStream(lib, out);

                out.flush();
                out.close();

            } catch (IOException e) {
                FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
                        "An error occured while generating the export file.");
                log.error("Could not open response-outputstream: ", e);
            }
            FacesContext.getCurrentInstance().responseComplete();
        } finally {
            OS.deleteDirectory(binarydataTempDir);
        }

    } else {
        FacesMessages.instance().add(FacesMessage.SEVERITY_INFO, "No Library found, create one first.");
    }
    System.gc();
    return null;
}

From source file:com.ab.http.AsyncHttpResponseHandler.java

/**
 * Gets the response data./*from w w  w  .  j av a2 s.  c o m*/
 *
 * @param entity the entity
 * @return the response data
 * @throws IOException Signals that an I/O exception has occurred.
 */
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");
            }
            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:gov.nasa.arc.geocam.geocam.CameraActivity.java

private void saveImage() {
    Log.d(GeoCamMobile.DEBUG_ID,//from ww w. j  a  v a2  s.  com
            "Saving orientation: " + mOrientation[2] + "," + mOrientation[1] + "," + mOrientation[0]);
    // Store orientation data in description field of mediastore using JSON encoding
    JSONObject imageData = new JSONObject();
    try {
        imageData.put("rpy", GeoCamMobile.rpySerialize(mOrientation[2], mOrientation[1], mOrientation[0]));
        imageData.put("yawRef", GeoCamMobile.YAW_MAGNETIC);
        imageData.put("uuid", UUID.randomUUID());
        Log.d(GeoCamMobile.DEBUG_ID, "Saving image with data: " + imageData.toString());
    } catch (JSONException e) {
        Log.d(GeoCamMobile.DEBUG_ID, "Error while adding JSON data to image");
    }
    mImageData = imageData;

    double lat, lon;
    if (mLocation == null) {
        lat = 0.0;
        lon = 0.0;
    } else {
        lat = mLocation.getLatitude();
        lon = mLocation.getLongitude();
    }

    // Add some parameters to the image that will be stored in the Image ContentProvider
    ContentValues values = new ContentValues();
    String name = String.valueOf(System.currentTimeMillis());
    values.put(MediaStore.Images.Media.DISPLAY_NAME, name + ".jpg");
    values.put(MediaStore.Images.Media.TITLE, name);
    values.put(MediaStore.Images.Media.DESCRIPTION, mImageData.toString());
    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    values.put(MediaStore.Images.Media.SIZE, mImageBytes.length);
    values.put(MediaStore.Images.Media.LATITUDE, lat);
    values.put(MediaStore.Images.Media.LONGITUDE, lon);

    // There appears to be a bug where saveImage() sometimes fails to actually create an entry 
    // in the db so we do one retry 
    int initNumEntries = getMediaStoreNumEntries();
    mImageUri = saveImage(values);
    if (getMediaStoreNumEntries() <= initNumEntries) {
        Log.d(GeoCamMobile.DEBUG_ID, "Retrying save");
        mImageUri = saveImage(values);
    }

    mImageBytes = null;
    Log.d(GeoCamMobile.DEBUG_ID, "Trying to force a GC");
    System.gc();

    dismissDialog(DIALOG_SAVE_PROGRESS);

    // Start camera preview activity
    Intent i = new Intent(Intent.ACTION_VIEW, mImageUri);
    i.setClass(getApplication(), CameraPreviewActivity.class);
    i.putExtra("data", mImageData.toString());
    startActivity(i);
}

From source file:com.wheelphone.remotemini.WheelphoneRemoteMini.java

/** NOTE: this method is synchronized because of a potential concurrent
 * access by FrameMarkers::onResume() and InitQCARTask::onPostExecute(). */
private synchronized void updateApplicationStatus(int appStatus) {
    // Exit if there is no change in status:
    if (mAppStatus == appStatus)
        return;//from   www.ja  va 2s  .c  o m

    // Store new status value
    mAppStatus = appStatus;

    // Execute application state-specific actions:
    switch (mAppStatus) {
    case APPSTATUS_INIT_APP:
        // Initialize application elements that do not rely on QCAR
        // initialization:
        initApplication();

        // Proceed to next application initialization status:
        updateApplicationStatus(APPSTATUS_INIT_QCAR);
        break;

    case APPSTATUS_INIT_QCAR:
        // Initialize QCAR SDK asynchronously to avoid blocking the
        // main (UI) thread.
        // This task instance must be created and invoked on the UI
        // thread and it can be executed only once!
        try {
            mInitQCARTask = new InitQCARTask();
            mInitQCARTask.execute();
        } catch (Exception e) {
            Log.e(TAG, "Initializing QCAR SDK failed");
        }
        break;

    case APPSTATUS_INIT_TRACKER:

        // Initialize the marker tracker and create markers:
        if (initTracker() >= 0) {
            Log.d(TAG, "Tracker initialized!\n");
            // Proceed to next application initialization status:
            updateApplicationStatus(APPSTATUS_INIT_APP_AR);
        }
        break;

    case APPSTATUS_INIT_APP_AR:
        // Initialize Augmented Reality-specific application elements
        // that may rely on the fact that the QCAR SDK has been
        // already initialized:
        initApplicationAR();

        // Proceed to next application initialization status:
        updateApplicationStatus(APPSTATUS_INITED);
        break;

    case APPSTATUS_INITED:
        // Hint to the virtual machine that it would be a good time to
        // run the garbage collector:
        //
        // NOTE: This is only a hint. There is no guarantee that the
        // garbage collector will actually be run.
        System.gc();

        //                // The elapsed time since the splash screen was visible:
        //                long splashScreenTime = System.currentTimeMillis() -
        //                                            mSplashScreenStartTime;
        //                long newSplashScreenTime = 0;
        //                if (splashScreenTime < MIN_SPLASH_SCREEN_TIME)
        //                {
        //                    newSplashScreenTime = MIN_SPLASH_SCREEN_TIME -
        //                                            splashScreenTime;
        //                }
        //
        //                // Request a callback function after a given timeout to dismiss
        //                // the splash screen:
        //                mSplashScreenHandler = new Handler();
        //                mSplashScreenRunnable =
        //                    new Runnable() {
        //                        public void run()
        //                        {
        //                            // Hide the splash screen:
        //                            mSplashScreenView.setVisibility(View.INVISIBLE);
        //
        //                            // Activate the renderer:
        //                            mRenderer.mIsActive = true;
        //
        //                            // Now add the GL surface view. It is important
        //                            // that the OpenGL ES surface view gets added
        //                            // BEFORE the camera is started and video
        //                            // background is configured.
        //                            addContentView(mGlView, new LayoutParams(
        //                                            LayoutParams.MATCH_PARENT,
        //                                            LayoutParams.MATCH_PARENT));
        //
        //                            // Start the camera:
        updateApplicationStatus(APPSTATUS_CAMERA_RUNNING);
        //                        }
        //                };
        //
        //                mSplashScreenHandler.postDelayed(mSplashScreenRunnable,
        //                                                    newSplashScreenTime);
        break;

    case APPSTATUS_CAMERA_STOPPED:
        // Call the native function to stop the camera:
        stopCamera();
        break;

    case APPSTATUS_CAMERA_RUNNING:
        // Call the native function to start the camera:
        startCamera();
        setProjectionMatrix();

        // Set continuous auto-focus if supported by the device,
        // otherwise default back to regular auto-focus mode.
        // This will be activated by a tap to the screen in this
        // application.
        mFocusMode = FOCUS_MODE_CONTINUOUS_AUTO;
        if (!setFocusMode(mFocusMode)) {
            mFocusMode = FOCUS_MODE_NORMAL;
            setFocusMode(mFocusMode);
        }

        break;

    default:
        throw new RuntimeException("Invalid application state");
    }
}

From source file:com.termmed.utils.FileHelper.java

/**
 * Gets the sorted file./*  w  w w .  j ava 2s  .  c  o m*/
 *
 * @param currFile the curr file
 * @param tempSortedFinalFolder the temp sorted final folder
 * @param tempSortingFolder the temp sorting folder
 * @param sortColumns the sort columns
 * @return the sorted file
 */
public static File getSortedFile(File currFile, File tempSortedFinalFolder, File tempSortingFolder,
        int[] sortColumns) {

    File sortedFile = new File(tempSortedFinalFolder, "Sorted" + currFile.getName());
    boolean sorted = isSorted(currFile, sortColumns);
    if (!sorted) {
        FileSorter fsc = new FileSorter(currFile, sortedFile, tempSortingFolder, sortColumns);
        fsc.execute();
        fsc = null;
        System.gc();
        return sortedFile;
    } else {
        return currFile;
    }

}