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.umd.cs.buildServer.BuildServer.java

/**
 * Execute the build server server loop.
 *
 * @throws IOException/*from   w  w w .  j a  v a 2  s . c  o m*/
 * @throws SecurityException
 */
public void executeServerLoop() throws Exception {
    configureBuildServerForMBeanManagement();
    if (alreadyRunning())
        return;
    try {
        markPid();
        createWorkingDirectories();
        this.log = createLog(getBuildServerConfiguration(), useServletAppender());
        log.info("BuildServer starting with pid " + MarmosetUtilities.getPid());

        {
            String load = SystemInfo.getSystemLoad();
            if (!SystemInfo.isGood(load))
                log.warn(load);
        }

        prepareToExecute();

        String supportedCourseList = getBuildServerConfiguration().getSupportedCourses();
        getLog().debug("Executing server loop; can build " + supportedCourseList);

        doWelcome();

        if (isVerifyOnly()) {
            System.out.println("verification only, terminating");
            return;
        }

        int overloadCount = 0;
        while (continueServerLoop()) {

            if (LoadAverage.isOverloaded()) {
                overloadCount++;
                getLog().warn("Build server overloaded, weighted load average" + " is "
                        + LoadAverage.getWeightedLoadAverage());
                if (overloadCount < 4)
                    continue;
            }
            overloadCount = 0;

            RequestStatus rc = doOneRequest();
            log.trace("Done with request");

            // Run GC, encourage finalizers to run
            if (rc == RequestStatus.ERROR) {
                ProcessKiller.killProcessGroup(MarmosetUtilities.getPid(), ProcessKiller.Signal.TERMINATION);
                // we shouldn't reach this point
                return;
            }

            System.gc();
            String load = SystemInfo.getSystemLoad();
            if (!SystemInfo.isGood(load))
                log.warn(load);
            // If there was no work, or if the project could
            // not be built due to an internal error,
            // sleep for a while. This will help avoid
            // thrashing the build server when nothing useful
            // can be done.
            if (rc == RequestStatus.NO_WORK || rc == RequestStatus.BUILD_FAILURE) {
                sleep();
            } else {
                noWorkCount = 0;
            }

            ++numServerLoopIterations;
        }

        getLog().debug("Server loop finished");
    } catch (Exception e) {
        getLog().error("Server loop terminating due to exception", e);
    } catch (Error e) {
        getLog().error("Server loop terminating due to error", e);
    } finally {
        clearMyPidFile();
    }
}

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

public static Bitmap getBitmapFromResource(Resources res, int resourceId, int maxSize) {
    Bitmap bitmap = null;//from  w  w w.  j a va2 s  .  co m
    int dummySize = maxSize * maxSize / 4; // KB
    while (bitmap == null && dummySize <= maxSize * maxSize * 4) {
        try {
            int sampleFactor = getSampleFactor(res, resourceId, maxSize);
            BitmapFactory.Options resample = new BitmapFactory.Options();
            resample.inSampleSize = sampleFactor;
            bitmap = BitmapFactory.decodeResource(res, resourceId, resample);
        } catch (Throwable e) {
            System.gc();
            // 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:Scheduler.java

/********************************************************************
 * Method: generatePermutations/*ww w .  j a  va2  s  .  c o  m*/
 * Purpose: generates all working permutations for current list (3rd Implementation)
/*******************************************************************/
public List<List<Course>> generatePermutations(List<List<Course>> workingSet) {

    // Try to persuade GC to run
    System.gc();
    Runtime.getRuntime().gc();

    try {

        // Reset exception
        exception = false;

        // Initialize three sets
        // One as a current iteration working area and another as iteration results
        // and last as memory for checking course sets
        //List<List<Course>> workingSet = new ArrayList<List<Course>>();
        workingSet.clear();
        List<List<Course>> newSet = new ArrayList<List<Course>>();
        List<Course> cloneSet = new ArrayList<Course>();

        // Memory for meeting lists
        List<Meeting> courseSubs = new ArrayList<Meeting>();

        // For each course
        for (String courseID : this.currentCourseList) {

            // For each section in the course
            for (Course course : this.catalog.get(courseID)) {

                if (workingSet.size() == 0) {

                    testClasses(new ArrayList<Course>(), course, cloneSet, courseSubs);
                    newSet.add(cloneSet);
                    cloneSet = new ArrayList<Course>();
                } else {
                    // Check all current workingSets
                    for (List<Course> courseSet : workingSet) {

                        // If fits into working set then add to newSet
                        if (testClasses(courseSet, course, cloneSet, courseSubs)) {
                            newSet.add(cloneSet);
                            cloneSet = new ArrayList<Course>();
                        } else {
                            cloneSet.clear();
                        }
                    }
                }
                if (exception)
                    break;
            }

            if (exception)
                break;

            // Update working set
            List<List<Course>> tempSet = workingSet;
            workingSet = newSet;
            newSet = tempSet;

            newSet.clear();
        }

        // Return working set
        this.exception = false;
        return workingSet;
    } catch (java.lang.OutOfMemoryError e) {
        this.exception = true;
        System.out.println("Out of memory.");
    }

    return null;
}

From source file:com.chtr.tmoauto.webui.CommonFunctions.java

@Override
public void quit() {
    if (webDriver != null) {
        System.gc();
        webDriver.quit();
    }
}

From source file:acmi.l2.clientmod.l2smr.Controller.java

private void initializeUnr() {
    mapsDirProperty().addListener((observable, oldValue, newValue) -> {
        unrChooser.getSelectionModel().clearSelection();
        unrChooser.getItems().clear();/*www .  j  av a2  s  .co m*/
        unrChooser.setDisable(true);

        if (newValue == null)
            return;

        unrChooser.getItems().addAll(Arrays.stream(newValue.listFiles(MAP_FILE_FILTER)).map(File::getName)
                .collect(Collectors.toList()));

        unrChooser.setDisable(false);

        AutoCompleteComboBox.autoCompleteComboBox(unrChooser, AutoCompleteComboBox.AutoCompleteMode.CONTAINING);
    });
    this.unrChooser.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        table.getSelectionModel().clearSelection();
        filterPane.setDisable(true);
        actors.set(null);
        actorStaticMeshChooser.getItems().clear();

        System.gc();

        if (newValue == null)
            return;

        try (UnrealPackage up = new UnrealPackage(new File(getMapsDir(), newValue), true)) {
            longTask(progress -> {
                List<UnrealPackage.ImportEntry> staticMeshes = up.getImportTable().parallelStream()
                        .filter(ie -> ie.getFullClassName().equalsIgnoreCase("Engine.StaticMesh"))
                        .sorted((ie1, ie2) -> String.CASE_INSENSITIVE_ORDER
                                .compare(ie1.getObjectInnerFullName(), ie2.getObjectInnerFullName()))
                        .collect(Collectors.toList());
                Platform.runLater(() -> {
                    actorStaticMeshChooser.getItems().setAll(staticMeshes);
                    AutoCompleteComboBox.autoCompleteComboBox(actorStaticMeshChooser,
                            AutoCompleteComboBox.AutoCompleteMode.CONTAINING);
                });

                List<Actor> actors = up
                        .getExportTable().parallelStream().filter(e -> UnrealPackage.ObjectFlag
                                .getFlags(e.getObjectFlags()).contains(UnrealPackage.ObjectFlag.HasStack))
                        .map(entry -> {
                            try {
                                return new Actor(entry.getIndex(), entry.getObjectInnerFullName(),
                                        entry.getObjectRawDataExternally(), up);
                            } catch (Throwable e) {
                                return null;
                            }
                        }).filter(Objects::nonNull)
                        .filter(actor -> actor.getStaticMeshRef() != 0 && actor.getOffsets().location != 0)
                        .collect(Collectors.toList());
                Platform.runLater(() -> Controller.this.actors.set(FXCollections.observableArrayList(actors)));
            }, e -> onException("Import failed", e));
        } catch (Exception e) {
            onException("Read failed", e);
        }

        resetFilter();
        filterPane.setDisable(false);
    });
    this.actorColumn.setCellValueFactory(actorStringCellDataFeatures -> new SimpleStringProperty(
            actorStringCellDataFeatures.getValue().getActorName()));
    this.staticMeshColumn.setCellValueFactory(actorStringCellDataFeatures -> new SimpleStringProperty(
            actorStringCellDataFeatures.getValue().getStaticMesh()));
    this.table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    this.table.getSelectionModel().selectedItemProperty().addListener((observable) -> updateSMAPane());

    this.table.setOnMouseClicked(event -> {
        if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
            String obj = table.getSelectionModel().getSelectedItem().getStaticMesh();
            String file = obj.substring(0, obj.indexOf('.')) + ".usx";
            showUmodel(obj, file);
        }
    });
}

From source file:org.agatom.springatom.cmp.wizards.core.CreateObjectWizardProcessor.java

/**
 * {@inheritDoc}/*from w w w.  jav a  2s.  c om*/
 */
@Override
@SuppressWarnings("UnusedAssignment")
public WizardResult onStepSubmit(final String step, final Map<String, Object> stepData, final Locale locale)
        throws Exception {
    LOGGER.debug(String.format("onStepSubmit(step=%s, stepData=%s)", step, stepData));

    final long startTime = System.nanoTime();
    final boolean isSubmitStep = StringUtils.hasText(step);

    if (LOGGER.isDebugEnabled() && isSubmitStep) {
        LOGGER.debug(String.format("step=%s therefore it is a step submit", step));
    }

    T contextObject = this.getContextObject();
    // Create appropriate binder.
    DataBinder binder = isSubmitStep ? this.createStepBinder(contextObject, step)
            : this.createGlobalBinder(contextObject);

    final ModelMap params = new ModelMap().addAllAttributes(stepData);
    final WizardResult finalResult = this.bind(binder, step, params, locale);

    if (!finalResult.hasErrors()) {
        LOGGER.debug(String.format("Bound to context object=%s without any error", contextObject));
        try {
            if (isSubmitStep) {
                final WizardResult localResult = this.submitStep(contextObject, params, step, locale);
                if (localResult != null) {
                    finalResult.merge(localResult);
                } else if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(String.format("%s does not execute any step submission", this.getWizardID()));
                }
            } else {
                finalResult.merge(this.submitWizard(contextObject, params, locale));
            }
        } catch (Exception submitExp) {
            LOGGER.error(String.format("Submission failed for contextObject=%s", contextObject), submitExp);
            finalResult.addError(submitExp);
            finalResult
                    .addFeedbackMessage(FeedbackMessage.newError().setMessage(submitExp.getLocalizedMessage()));
        } finally {
            binder.close();
        }
    }

    final long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(
                String.format("submitStep(step=%s, stepData=%s) executed in %d ms", step, stepData, endTime));
    }

    finalResult.addDebugData(WizardDebugDataKeys.TOTAL_TIME, endTime);
    finalResult.addDebugData(WizardDebugDataKeys.PROCESSOR, ClassUtils.getShortName(this.getClass()));
    finalResult.addDebugData(WizardDebugDataKeys.LOCALE, locale);

    // collect garbage
    binder = null;
    contextObject = null;
    System.gc();

    return finalResult;
}

From source file:gui.DownloadManagerGUI.java

public DownloadManagerGUI(String name) {
    super(name);//w w w .j a  va  2 s.  c o  m

    setLayout(new BorderLayout());

    preferences = Preferences.userRoot().node("db");
    final PreferencesDTO preferencesDTO = getPreferences();

    LookAndFeel.setLaf(preferencesDTO.getPreferencesInterfaceDTO().getLookAndFeelName());

    createFileHierarchy();

    mainToolbar = new MainToolBar();
    categoryPanel = new CategoryPanel(
            preferencesDTO.getPreferencesSaveDTO().getPreferencesDirectoryCategoryDTOs());
    downloadPanel = new DownloadPanel(this, preferencesDTO.getPreferencesSaveDTO().getDatabasePath(),
            preferencesDTO.getPreferencesConnectionDTO().getConnectionTimeOut(),
            preferencesDTO.getPreferencesConnectionDTO().getReadTimeOut());
    messagePanel = new MessagePanel(this);
    JTabbedPane mainTabPane = new JTabbedPane();
    mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, categoryPanel, mainTabPane);
    mainSplitPane.setOneTouchExpandable(true);
    statusPanel = new StatusPanel();
    addNewDownloadDialog = new AddNewDownloadDialog(this);

    mainTabPane.addTab(messagesBundle.getString("downloadManagerGUI.mainTabPane.downloadPanel"), downloadPanel);
    mainTabPane.addTab(messagesBundle.getString("downloadManagerGUI.mainTabPane.messagePanel"), messagePanel);

    preferenceDialog = new PreferenceDialog(this, preferencesDTO);

    aboutDialog = new AboutDialog(this);

    categoryPanel.setCategoryPanelListener((fileExtensions, downloadCategory) -> downloadPanel
            .setDownloadsByDownloadPath(fileExtensions, downloadCategory));

    //     preferenceDialog.setDefaults(preferencesDTO);

    addNewDownloadDialog.setAddNewDownloadListener(textUrl -> {
        Objects.requireNonNull(textUrl, "textUrl");
        if (textUrl.equals(""))
            throw new IllegalArgumentException("textUrl is empty");

        String downloadName;
        try {
            downloadName = ConnectionUtil.getRealFileName(textUrl);
        } catch (IOException e) {
            logger.error("Can't get real name of file that you want to download." + textUrl);
            messageLogger.error("Can't get real name of file that you want to download." + textUrl);
            downloadName = ConnectionUtil.getFileName(textUrl);
        }
        String fileExtension = FilenameUtils.getExtension(downloadName);
        File downloadPathFile = new File(
                preferencesDTO.getPreferencesSaveDTO().getPathByFileExtension(fileExtension));
        File downloadRangeFile = new File(preferencesDTO.getPreferencesSaveDTO().getTempDirectory());
        int maxNum = preferencesDTO.getPreferencesConnectionDTO().getMaxConnectionNumber();

        Download download = null;

        List<Download> downloads = downloadPanel.getDownloadList();
        String properDownloadName = getProperNameForDownload(downloadName, downloads, downloadPathFile);

        // todo must set stretegy pattern
        switch (ProtocolType.valueOfByDesc(textUrl.getProtocol())) {
        case HTTP:
            download = new HttpDownload(downloadPanel.getNextDownloadID(), textUrl, properDownloadName, maxNum,
                    downloadPathFile, downloadRangeFile, ProtocolType.HTTP);
            break;
        case FTP:
            // todo must be created ...
            break;
        case HTTPS:
            download = new HttpsDownload(downloadPanel.getNextDownloadID(), textUrl, properDownloadName, maxNum,
                    downloadPathFile, downloadRangeFile, ProtocolType.HTTPS);
            break;
        }

        downloadPanel.addDownload(download);
    });

    // Add panels to display.
    add(mainToolbar, BorderLayout.PAGE_START);
    add(mainSplitPane, BorderLayout.CENTER);
    add(statusPanel, BorderLayout.PAGE_END);

    setJMenuBar(initMenuBar());

    mainToolbar.setMainToolbarListener(new MainToolbarListener() {
        @Override
        public void newDownloadEventOccured() {
            addNewDownloadDialog.setVisible(true);
            addNewDownloadDialog.onPaste();
        }

        @Override
        public void pauseEventOccured() {
            downloadPanel.actionPause();
            mainToolbar.setStateOfButtonsControl(false, false, false, false, false, true); // canceled
        }

        @Override
        public void resumeEventOccured() {
            downloadPanel.actionResume();
        }

        @Override
        public void pauseAllEventOccured() {
            downloadPanel.actionPauseAll();
        }

        @Override
        public void clearEventOccured() {
            downloadPanel.actionClear();
        }

        @Override
        public void clearAllCompletedEventOccured() {
            downloadPanel.actionClearAllCompleted();
        }

        @Override
        public void reJoinEventOccured() {
            downloadPanel.actionReJoinFileParts();
        }

        @Override
        public void reDownloadEventOccured() {
            downloadPanel.actionReDownload();
        }

        @Override
        public void propertiesEventOccured() {
            downloadPanel.actionProperties();
        }

        @Override
        public void preferencesEventOccured() {
            preferenceDialog.setVisible(true);
        }
    });

    downloadPanel.setDownloadPanelListener(new DownloadPanelListener() {
        @Override
        public void stateChangedEventOccured(DownloadStatus downloadState) {
            updateButtons(downloadState);
        }

        @Override
        public void downloadSelected(Download download) {
            statusPanel.setStatus(download.getDownloadName());
        }
    });

    preferenceDialog.setPreferencesListener(new PreferencesListener() {
        @Override
        public void preferencesSet(PreferencesDTO preferenceDTO) {
            setPreferencesOS(preferenceDTO);
        }

        @Override
        public void preferenceReset() {
            PreferencesDTO resetPreferencesDTO = getPreferences();
            preferenceDialog.setPreferencesDTO(resetPreferencesDTO);
            categoryPanel.setTreeModel(
                    resetPreferencesDTO.getPreferencesSaveDTO().getPreferencesDirectoryCategoryDTOs());
        }

        @Override
        public void preferenceDefaults() {
            PreferencesDTO defaultPreferenceDTO = new PreferencesDTO();
            resetAndSetPreferencesDTOFromConf(defaultPreferenceDTO);
            preferenceDialog.setPreferencesDTO(defaultPreferenceDTO);
            categoryPanel.setTreeModel(
                    defaultPreferenceDTO.getPreferencesSaveDTO().getPreferencesDirectoryCategoryDTOs());
        }
    });

    // Handle window closing events.
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent windowEvent) {
            int action = JOptionPane.showConfirmDialog(DownloadManagerGUI.this,
                    "Do you realy want to exit the application?", "Confirm Exit", JOptionPane.OK_CANCEL_OPTION);
            if (action == JOptionPane.OK_OPTION) {
                logger.info("Window Closing");
                downloadPanel.actionPauseAll();
                dispose();
                System.gc();
            }
        }
    });

    Authenticator.setDefault(new DialogAuthenticator(this));

    setIconImage(
            Utils.createIcon(messagesBundle.getString("downloadManagerGUI.mainFrame.iconPath")).getImage());

    setMinimumSize(new Dimension(640, 480));
    // Set window size.
    pack();
    setSize(900, 580);

    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    setVisible(true);
}

From source file:de.juwimm.cms.remote.EditionServiceSpringImpl.java

private Document getDocumentFromFile(File preparsedXMLfile, String editionFileName) throws Exception {
    if (log.isInfoEnabled())
        log.info("Finished writing Edition to File, starting to import it as GZIP-InputStream...");
    XMLFilter filter = new XMLFilterImpl(XMLReaderFactory.createXMLReader());
    preparsedXMLfile = File.createTempFile("edition_import_preparsed_", ".xml");
    if (log.isDebugEnabled())
        log.debug("preparsedXMLfile: " + preparsedXMLfile.getAbsolutePath());
    XMLWriter xmlWriter = new XMLWriter(new OutputStreamWriter(new FileOutputStream(preparsedXMLfile)));
    filter.setContentHandler(new EditionBlobContentHandler(xmlWriter, preparsedXMLfile));
    InputSource saxIn = null;//w w  w.  jav a 2s. c  om
    try {
        try {
            saxIn = new InputSource(new GZIPInputStream(new FileInputStream(editionFileName)));
        } catch (Exception exe) {
            saxIn = new InputSource(new BufferedReader(new FileReader(editionFileName)));
        }
    } catch (FileNotFoundException exe) {
        log.error("Edition file isnt available anymore. Edition needs to be deleted!");
    }
    filter.parse(saxIn);
    xmlWriter.flush();
    xmlWriter = null;
    filter = null;
    System.gc();
    if (log.isInfoEnabled())
        log.info("Finished cutting BLOBs, starting to open XML Document...");
    // BufferedReader br = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
    // InputSource in = new InputSource(br);
    InputSource domIn = new InputSource(new FileInputStream(preparsedXMLfile));
    return XercesHelper.inputSource2Dom(domIn);
}

From source file:org.lareferencia.backend.tasks.SnapshotWorker.java

/**
 * TODO: Podra ser Async, pero no tiene sentido empezar un nuevo proceso de harvesting para una misma red si el anterior
 * no termin. Hay que cuidar los bloqueos!!! TODO: Podra implemetarse la limpieza de procesos inactivos para evitar problemas
 * @throws Exception /*from  w  w w .j ava2s.c om*/
 */
@Override
public void run() {

    boolean newSnapshotCreated = true;

    if (snapshotID != null) { // Este es el caso en que se retorma un snapshot bloqueado 

        snapshot = snapshotRepository.findOne(snapshotID);

        if (snapshot != null && snapshot.getStatus().equals(SnapshotStatus.HARVESTING_STOPPED)) { // tiene que estar detenido

            network = snapshot.getNetwork();
            newSnapshotCreated = false;

            // cambia el status
            setSnapshotStatus(SnapshotStatus.HARVESTING);

        } else {
            System.err.println(
                    "El snapshot no existe o est ya est siendo procesado. El worker no puede continuar");
            return;
        }

    } else { // este es el caso donde se inicia un nuevo snapshot

        network = networkRepository.findOne(networkID);

        if (network != null) {
            snapshot = new NetworkSnapshot();
            snapshot.setNetwork(network);
            snapshotRepository.save(snapshot);
        } else {
            System.err.println("La Red no existe!! El worker no puede continuar");
            return;
        }

    }

    // Se cargan el validador y el transformador de acuerdo a la configuracin de la red
    try {
        logMessage("Cargando validador y transformador  ...");

        validator = applicationContext.getBean(network.getValidatorName(), IValidator.class);
        transformer = applicationContext.getBean(network.getTransformerName(), ITransformer.class);

    } catch (Exception e) {
        logMessage("Error en la carga del validador o transformador, vea el log para ms detalles.");
        setSnapshotStatus(SnapshotStatus.HARVESTING_FINISHED_ERROR);
        return;
    }

    // Se carga el helper para la resolucin de nombre de repositorios
    repositoryNameHelper = new RepositoryNameHelper();
    repositoryNameHelper.setDetectREPattern(repoNameDetectionPatternString);

    // Se registra el incicio de tareas en el manager
    manager.registerWorkerBeginSnapshot(snapshot.getId(), this);

    logMessage("Comenzando cosecha ...");
    setSnapshotStatus(SnapshotStatus.HARVESTING);

    // harvest de la red

    // inicializacin del harvester
    harvester.reset();

    if (newSnapshotCreated) // caso de harvesting desde cero

        if (harvestBySet)
            harvestEntireNetworkBySet();
        else
            harvestEntireNetwork();

    else // caso de retomar desde un rt anterior
        harvestNetworkFromRT(snapshot.getResumptionToken());

    // Luego del harvesting el snapshot puede presentar estados diversos

    // si no fue detenido
    if (snapshot.getStatus() != SnapshotStatus.HARVESTING_STOPPED) {

        // Si no gener errores, entonces termin exitosa la cosecha
        if (snapshot.getStatus() != SnapshotStatus.HARVESTING_FINISHED_ERROR) {

            logMessage("Cosecha terminada en forma exitosa");
            logMessage("Comenzando indexacin ...");

            // Graba el status
            snapshot.setEndTime(new Date());
            setSnapshotStatus(SnapshotStatus.INDEXING);

            // Si est publicada la red y es una red que se indexa
            if (network.isRunIndexing() && network.isPublished()) {

                // Indexa
                boolean isSuccesfullyIndexed = indexer.index(snapshot);

                // Si el indexado es exitoso marca el snap vlido
                if (isSuccesfullyIndexed) {
                    // Graba el status
                    setSnapshotStatus(SnapshotStatus.VALID);

                    logMessage("Indexacin terminada con xito.");
                } else {
                    // Graba el status
                    setSnapshotStatus(SnapshotStatus.INDEXING_FINISHED_ERROR);

                    logMessage("Error en proceso de indexacin.");
                }
            } else {
                // si no est publicada o no se indexa la marca como vlida sin indexar
                // Graba el status
                setSnapshotStatus(SnapshotStatus.VALID);

                // Almacena los resultados de las statsticas de metadatatos
                if (network.isRunStats()) {
                    saveSnapshotMetadataStats(originalMetadataStatsManager.getStats());
                    saveSnapshotMetadataStats(transformedMetadataStatsManager.getStats());
                }

            }

        } else {
            logMessage("Cosecha finalizada con errores");
        }
    }

    snapshot.setEndTime(new Date());
    snapshotRepository.save(snapshot);

    // Flush y llamados al GC
    snapshotRepository.flush();

    // Se registra el fin de tareas en el manager
    manager.registerWorkerEndSnapshot(snapshot.getId());

    System.gc();
}

From source file:com.spoiledmilk.ibikecph.util.Util.java

public static Bitmap bmpDecodeFile(File f, int width_limit, int height_limit, long max_size,
        boolean max_dimensions) {
    if (f == null) {
        return null;
    }//from w w  w.j a v a 2s .co  m

    LOG.d("bmpDecodeFile(" + f.getAbsolutePath() + "," + width_limit + "," + height_limit + "," + max_size + ","
            + max_dimensions + ")");

    Bitmap bmp = null;
    boolean shouldReturn = false;

    FileInputStream fin = null;
    int orientation = ExifInterface.ORIENTATION_NORMAL;
    try {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        fin = new FileInputStream(f);
        BitmapFactory.decodeStream(fin, null, o);
        try {
            fin.close();
            fin = null;
        } catch (IOException e) {
        }

        // Find the correct scale value. It should be the power of 2.
        int scale = 1;
        if (width_limit != -1 && height_limit != -1) {
            if (max_dimensions) {
                while (o.outWidth / scale > width_limit || o.outHeight / scale > height_limit)
                    scale *= 2;
            } else {
                while (o.outWidth / scale / 2 >= width_limit && o.outHeight / scale / 2 >= height_limit)
                    scale *= 2;
            }
        } else if (max_size != -1)
            while ((o.outWidth * o.outHeight) / (scale * scale) > max_size)
                scale *= 2;

        // Decode with inSampleSize
        o = null;
        if (scale > 1) {
            o = new BitmapFactory.Options();
            o.inSampleSize = scale;
        }
        fin = new FileInputStream(f);
        try {
            bmp = BitmapFactory.decodeStream(fin, null, o);
        } catch (OutOfMemoryError e) {
            // Try to recover from out of memory error - but keep in mind
            // that behavior after this error is
            // undefined,
            // for example more out of memory errors might appear in catch
            // block.
            if (bmp != null)
                bmp.recycle();
            bmp = null;
            System.gc();
            LOG.e("Util.bmpDecodeFile() OutOfMemoryError in decodeStream()! Trying to recover...");
        }

        if (bmp != null) {
            LOG.d("resulting bitmap width : " + bmp.getWidth() + " height : " + bmp.getHeight() + " size : "
                    + (bmp.getRowBytes() * bmp.getHeight()));

            ExifInterface exif = new ExifInterface(f.getPath());
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        }
    } catch (FileNotFoundException e) {
        shouldReturn = true;
    } catch (IOException e) {
        shouldReturn = true; // bitmap is still valid here, just can't be
        // rotated
    } finally {
        if (fin != null)
            try {
                fin.close();
            } catch (IOException e) {
            }
    }

    if (shouldReturn || bmp == null)
        return bmp;

    float rotate = 0;
    switch (orientation) {
    case ExifInterface.ORIENTATION_ROTATE_90:
        rotate = 90;
        break;
    case ExifInterface.ORIENTATION_ROTATE_180:
        rotate = 180;
        break;
    case ExifInterface.ORIENTATION_ROTATE_270:
        rotate = 270;
        break;
    }
    if (rotate > 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotate);
        Bitmap bmpRot = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        matrix = null;
        bmp.recycle();
        bmp = null;
        // System.gc();
        return bmpRot;
    }

    return bmp;
}