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:hudson.remoting.RegExpBenchmark.java

@Test
public void repeatedBenchMark() throws Exception {
    for (int i = 0; i < 10; i++) {
        benchmark();/*from   ww  w. ja v  a2s  . c  om*/
        System.gc();
        System.gc();
        System.gc();
    }
}

From source file:com.imagelake.control.CreditsDAOImp.java

@Override
public List<Credits> getCreditList() {
    List<Credits> clis = new ArrayList<Credits>();
    try {//from   ww  w  .  j a va2  s.c  o m
        String sql = "SELECT * FROM credits";
        PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql);

        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            Credits c = new Credits();
            c.setCredit_id(rs.getInt(1));
            c.setCredits(rs.getInt(2));
            c.setSize(rs.getString(3));
            c.setWidth(rs.getInt(4));
            c.setHeight(rs.getInt(5));
            c.setState(rs.getInt(6));
            clis.add(c);
            System.gc();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return clis;
}

From source file:heigit.ors.servlet.listeners.ORSInitContextListener.java

public void contextDestroyed(ServletContextEvent contextEvent) {
    try {//from  w w w . ja  va2s .c  o  m
        LOGGER.info("Start shutting down ORS and releasing resources.");

        if (RoutingProfileManagerStatus.isReady())
            RoutingProfileManager.getInstance().destroy();

        StatisticsProviderFactory.releaseProviders();

        LogFactory.release(Thread.currentThread().getContextClassLoader());

        try {
            System.gc();
            System.runFinalization();
            System.gc();
            System.runFinalization();
        } catch (Throwable t) {
            LOGGER.error("Failed to perform finalization.");
            t.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * A safer decodeStream method/*  w  w  w . j a va  2  s .  c o  m*/
 * rather than the one of {@link BitmapFactory} which will be easy to get OutOfMemory Exception
 * while loading a big image file.
 * 
 * @param uri
 * @param width
 * @param height
 * @return
 * @throws FileNotFoundException
 */
protected static Bitmap safeDecodeStream(Context context, Uri uri, int width, int height)
        throws FileNotFoundException {
    int scale = 1;
    // Decode image size without loading all data into memory  
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    android.content.ContentResolver resolver = context.getContentResolver();
    try {

        BitmapFactory.decodeStream(new BufferedInputStream(resolver.openInputStream(uri), 4 * 1024), null,
                options);
        if (width > 0 || height > 0) {
            options.inJustDecodeBounds = true;
            int w = options.outWidth;
            int h = options.outHeight;
            while (true) {
                if ((width > 0 && w / 2 < width) || (height > 0 && h / 2 < height)) {
                    break;
                }
                w /= 2;
                h /= 2;
                scale *= 2;
            }
        }
        // Decode with inSampleSize option  
        options.inJustDecodeBounds = false;
        options.inSampleSize = scale;
        return BitmapFactory.decodeStream(new BufferedInputStream(resolver.openInputStream(uri), 4 * 1024),
                null, options);
    } catch (Exception e) {
        e.printStackTrace();
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
    }
    return null;
}

From source file:com.cura.Terminal.Terminal.java

public synchronized String ExecuteCommand(String command) {

    try {/*ww w .j ava  2 s. c  o m*/
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.connect();

        // get output from server
        in = channel.getInputStream();

        // convert output to string
        writer.getBuffer().setLength(0);
        IOUtils.copy(in, writer);
        result = writer.toString();

        System.gc();

    } catch (IOException i) {
        Log.d("terminal", i.toString());
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        Log.d("terminal", e.toString());
    }
    return result;
}

From source file:edu.stanford.mobisocial.dungbeetle.obj.action.ExportPhotoAction.java

@Override
public void onAct(Context context, DbEntryHandler objType, DbObj obj) {
    byte[] raw = obj.getRaw();
    if (raw == null) {
        String b64Bytes = obj.getJson().optString(PictureObj.DATA);
        raw = FastBase64.decode(b64Bytes);
    }// ww w.  j av a2  s  . co  m
    OutputStream outStream = null;
    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp_share.png");
    try {
        outStream = new FileOutputStream(file);

        BitmapManager mgr = new BitmapManager(1);
        Bitmap bitmap = mgr.getBitmap(raw.hashCode(), raw);

        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
        outStream.flush();
        outStream.close();

        bitmap.recycle();
        bitmap = null;
        System.gc();
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("image/png");
        Log.w("ResharePhotoAction",
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp_share.png");
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        context.startActivity(Intent.createChooser(intent, "Export image to"));

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:edu.unc.lib.dl.ingest.aip.AIPIngestPipeline.java

/**
 * Takes an IngestContext and runs all the configured filters that make up the ingest processing pipeline. It returns
 * an IngestContext that is ready for storage in a Fedora repository.
 *
 * The repositoryPath may be passed along by the calling context or left null if the SIP either contains a collection
 * or specifies it's parent in PREMIS. Any combination of repository path strategies will throw an error.
 *
 * @param sipzip/*  w w w.ja va  2  s.com*/
 *           a SIP archive file
 * @param repositoryPath
 *           this is the path in which the SIP objects are placed.
 * @return an XML ingest report
 */
public ArchivalInformationPackage processAIP(ArchivalInformationPackage aip) throws IngestException {
    try {
        for (AIPIngestFilter filter : this.preIngestFilters) {
            aip = filter.doFilter(aip);
        }
    } catch (AIPException e) {
        // Log all recognized ingest filter exception cases in the
        // IngestException.
        aip.getEventLogger().logException("There was an unexpected exception.", e);
        Element report = aip.getEventLogger().getAllEvents();
        aip.delete();
        IngestException throwing = new IngestException(e.getMessage(), e);
        throwing.setErrorXML(report);
        throw throwing;
    }
    System.gc();
    return aip;
}

From source file:Main.java

/**
 * Deletes an individual file or a directory. A recursive deletion can be
 * forced as well. The garbage collector can be run once before attempting
 * to delete, to workaround lock issues under Windows operating systems.
 * //from   w  w  w . j  av a  2s.c  o m
 * @param file
 *            The individual file or directory to delete.
 * @param recursive
 *            Indicates if directory with content should be deleted
 *            recursively as well.
 * @param garbageCollect
 *            Indicates if the garbage collector should be run.
 * @return True if the deletion was successful or if the file or directory
 *         didn't exist.
 */
public static boolean delete(java.io.File file, boolean recursive, boolean garbageCollect) {
    boolean result = true;
    boolean runGC = garbageCollect;

    if (file.exists()) {
        if (file.isDirectory()) {
            java.io.File[] entries = file.listFiles();

            // Check if the directory is empty
            if (entries.length > 0) {
                if (recursive) {
                    for (int i = 0; result && (i < entries.length); i++) {
                        if (runGC) {
                            System.gc();
                            runGC = false;
                        }

                        result = delete(entries[i], true, false);
                    }
                } else {
                    result = false;
                }
            }
        }

        if (runGC) {
            System.gc();
            runGC = false;
        }

        result = result && file.delete();
    }

    return result;
}

From source file:com.thesmartweb.swebrank.Moz.java

/**
 * Method that captures the various Moz metrics for the provided urls (with help of the sample here https://github.com/seomoz/SEOmozAPISamples
 * and ranks them accordingly/* www .  j a va2  s  .  com*/
 * @param links the urls to analyze
 * @param top_count the amount of results to keep when we rerank the results according to their value of a specific Moz metric
 * @param moz_threshold the threshold to the Moz value to use
 * @param moz_threshold_option flag if we are going to use threshold in the Moz value or not
 * @param mozMetrics list that contains which metric to use for Moz //1st place is Page Authority,2nd external mozRank, 3rd, mozTrust, 4th DomainAuthority and 5th MozRank (it is the default)
 * @param config_path path that has the config files with the api keys and secret for Moz
 * @return an array with the links sorted according to their moz values
 */
public String[] perform(String[] links, int top_count, Double moz_threshold, Boolean moz_threshold_option,
        List<Boolean> mozMetrics, String config_path) {
    //=====short codes for the metrics 
    long upa = 34359738368L;//page authority
    long pda = 68719476736L;//domain authority
    long uemrp = 1048576;//mozrank external equity
    long utrp = 131072;//moztrust 
    long fmrp = 32768;//mozrank subdomain
    long umrp = 16384;//mozrank
    System.gc();
    System.out.println("into Moz");
    Double[] mozRanks = new Double[links.length];
    DataManipulation textualmanipulation = new DataManipulation();
    for (int i = 0; i < links.length; i++) {
        if (links[i] != null) {
            if (!textualmanipulation.StructuredFileCheck(links[i])) {
                try {
                    Thread.sleep(10000);
                    URLMetricsService urlMetricsservice;
                    urlMetricsservice = authenticate(config_path);
                    String objectURL = links[i].substring(0, links[i].length());
                    Gson gson = new Gson();
                    if (mozMetrics.get(1)) {//Domain Authority
                        String response = urlMetricsservice.getUrlMetrics(objectURL, pda);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getPda();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    } else if (mozMetrics.get(2)) {//External MozRank
                        String response = urlMetricsservice.getUrlMetrics(objectURL, uemrp);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getUemrp();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    } else if (mozMetrics.get(3)) {//MozRank
                        String response = urlMetricsservice.getUrlMetrics(objectURL, umrp);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getUmrp();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    } else if (mozMetrics.get(4)) {//MozTrust
                        String response = urlMetricsservice.getUrlMetrics(objectURL, utrp);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getUtrp();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    } else if (mozMetrics.get(5)) {//Page Authority
                        String response = urlMetricsservice.getUrlMetrics(objectURL, upa);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getUpa();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    } else if (mozMetrics.get(6)) {//subdomain MozRank
                        String response = urlMetricsservice.getUrlMetrics(objectURL, fmrp);
                        UrlResponse res = gson.fromJson(response, UrlResponse.class);
                        System.gc();
                        if (res != null && !(response.equalsIgnoreCase("{}"))) {
                            String mozvalue_string = res.getFmrp();
                            mozRanks[i] = Double.parseDouble(mozvalue_string);
                        } else {
                            mozRanks[i] = Double.parseDouble("0");
                        }
                    }
                } catch (InterruptedException | JsonSyntaxException | NumberFormatException ex) {
                    System.out.println("exception moz:" + ex.toString());
                    mozRanks[i] = Double.parseDouble("0");
                    String[] links_out = null;
                    return links_out;
                }
            } else {
                mozRanks[i] = Double.parseDouble("0");
            }
        }
    }
    try {//ranking of the urls according to their moz score
         //get the scores to a list
        System.out.println("I am goint to rank the scores of Moz");
        System.gc();
        List<Double> seomozRanks_scores_list = Arrays.asList(mozRanks);
        //create a hashmap in order to map the scores with the indexes
        System.gc();
        IdentityHashMap<Double, Integer> originalIndices = new IdentityHashMap<Double, Integer>();
        //copy the original scores list
        System.gc();
        for (int i = 0; i < seomozRanks_scores_list.size(); i++) {
            originalIndices.put(seomozRanks_scores_list.get(i), i);
            System.gc();
        }
        //sort the scores
        List<Double> sorted_seomozRanks_scores = new ArrayList<Double>();
        System.gc();
        sorted_seomozRanks_scores.addAll(seomozRanks_scores_list);
        System.gc();
        sorted_seomozRanks_scores.removeAll(Collections.singleton(null));
        System.gc();
        if (!sorted_seomozRanks_scores.isEmpty()) {
            Collections.sort(sorted_seomozRanks_scores, Collections.reverseOrder());
        }
        //get the original indexes
        //the max amount of results
        int[] origIndex = new int[150];
        if (!sorted_seomozRanks_scores.isEmpty()) {
            //if we want to take the top scores(for example top 10)
            if (!moz_threshold_option) {
                origIndex = new int[top_count];
                for (int i = 0; i < top_count; i++) {
                    Double score = sorted_seomozRanks_scores.get(i);
                    System.gc();
                    // Lookup original index efficiently
                    origIndex[i] = originalIndices.get(score);
                }
            }
            //if we have a threshold
            else if (moz_threshold_option) {
                int j = 0;
                int counter = 0;
                while (j < sorted_seomozRanks_scores.size()) {
                    if (sorted_seomozRanks_scores.get(j).compareTo(moz_threshold) >= 0) {
                        counter++;
                    }
                    j++;
                }
                origIndex = new int[counter];
                for (int k = 0; k < origIndex.length - 1; k++) {
                    System.gc();
                    Double score = sorted_seomozRanks_scores.get(k);
                    origIndex[k] = originalIndices.get(score);
                }
            }
        }
        String[] links_out = new String[origIndex.length];
        for (int jj = 0; jj < origIndex.length; jj++) {
            System.gc();
            links_out[jj] = links[origIndex[jj]];
        }
        System.gc();
        System.out.println("I have ranked the scores of moz");
        return links_out;
    } catch (Exception ex) {
        System.out.println("exception moz list" + ex.toString());
        //Logger.getLogger(Moz.class.getName()).log(Level.SEVERE, null, ex);
        String[] links_out = null;
        return links_out;
    }
}

From source file:com.imagelake.control.InterfaceDAOImp.java

public Interfaces getInterface(String name) {
    Interfaces inf = null;/*  www  . j  a v  a2  s .  c om*/
    try {
        String ql = "SELECT * FROM interfaces WHERE url=?";
        PreparedStatement ps = DBFactory.getConnection().prepareStatement(ql);
        ps.setString(1, name);
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {
            inf = new Interfaces();
            inf.setInterface_id(rs.getInt(1));
            inf.setDisplay_name(rs.getString(3));
            inf.setUrl(rs.getString(2));
            inf.setState(rs.getInt(4));
            System.gc();

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return inf;
}