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:com.elastica.helper.FileUtility.java

/**
 * Saves HTML Source./*from   w w w .ja v  a 2s.  c o  m*/
 *
 * @param   path
 *
 * @throws  Exception
 */

public static void writeToFile(final String path, final String content) throws IOException {

    System.gc();

    FileOutputStream fileOutputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    BufferedWriter bw = null;
    try {
        File parentDir = new File(path).getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        fileOutputStream = new FileOutputStream(path);
        outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF8");
        bw = new BufferedWriter(outputStreamWriter);
        bw.write(content);
    } finally {
        if (bw != null) {
            try {
                bw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (outputStreamWriter != null) {
            try {
                outputStreamWriter.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.slytechs.capture.file.editor.FileEditorImpl.java

/**
 * <p>//www  .j a va  2s  .c om
 * Flushes all the changes made so far to the underlying file. If no changes
 * have been made, nothing happens. Changes are flushed to the underlying file
 * and the edits hierarchy is flattened. Any previously aquired change
 * iterators should be discarded and new ones aquired. Any attempt to use them
 * will throw InvalidRegionException since all changes have been invalidated.
 * Forwarding to the new edits tree will forward any RegionHandles to new
 * RegionOverlays which now contain the flattened changes.
 * </p>
 * <p>
 * The algorithm in this flush method is optimized for changes that simply
 * append record to the end. If anyother type of changes, besides the appended
 * records, have been applied, the changes are flushed using a more generic
 * algrorithm that ensure entegrity of the entire file.
 * </p>
 * 
 * @see java.io.Flushable#flush()
 */
public void flush() throws IOException {

    if (this.isModified() == false) {

        return;
    }

    if (this.edits.isModifiedByAppendOnly()) {
        this.flushByAppendInPlace();
    } else {
        /*
         * We flatten inside inorder to release any Memory MAPPED regions before
         * closing the source channel
         */
        this.flushByCopy();
    }

    final PartialLoader loader = new PartialFileLoader(this.channel, this.mode, this.headerReader, file);
    loader.order(this.order);
    this.edits.flatten(loader);

    System.gc();

    this.totalChange = 0;
}

From source file:net.sf.jclal.activelearning.algorithm.ClassicalALAlgorithm.java

/**
 * Clean the memory
 */
protected void doClean() {

    // Run the GC
    System.gc();

}

From source file:com.joliciel.jochre.graphics.JochreImageImpl.java

@Override
public void clearMemory() {
    this.paragraphs = null;
    this.originalImage = null;
    this.pixelGrabber = null;
    this.shapeMap = null;
    System.gc();
}

From source file:com.imagelake.android.details.Servlet_ImageDetails.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {//from   www .  j  a v a 2s. c o m
        String type = request.getParameter("type");
        System.out.println(type);
        if (!type.equals("") && type != null) {

            if (type.equals("info")) {
                String imgid = request.getParameter("imgid");
                String uid = request.getParameter("uid");

                Images img = idip.getImageDetail(Integer.parseInt(imgid));

                if (img != null) {
                    boolean k = new ImagesDAOImp().updateImageViewCount(img.getImages_id(), img.getView() + 1);
                    if (k) {
                        if (img.getImage_state_image_state_id() == 1) {
                            detailObject = new JSONObject();
                            detailObject.put("title", img.getTitle());
                            detailObject.put("url", img.getImg_url());
                            detailObject.put("view", img.getView());
                            int chh = cdi.getCartDownloadCount(Integer.parseInt(imgid));
                            detailObject.put("dwn", chh);

                            JSONArray subImagesArray = new JSONArray();
                            Credits cre;
                            List<ImagesSub> subList = idip.getImagedescription(Integer.parseInt(imgid));
                            for (ImagesSub imagesSub : subList) {
                                JSONObject jo = new JSONObject();
                                cre = crdi.getCreditDetails(imagesSub.getCredits());

                                jo.put("sid", imagesSub.getSub_images_id());
                                jo.put("size", cre.getSize());
                                jo.put("dim", imagesSub.getDimention());
                                jo.put("crd", cre.getCredits());

                                subImagesArray.add(jo);

                            }
                            detailObject.put("subList", subImagesArray);

                            User u = udi.getUser(img.getUser_user_id());
                            detailObject.put("uName", u.getUser_name());

                            List<KeyWords> keyList = kdi.getkeyWordList(Integer.parseInt(imgid));
                            JSONArray keyArray = new JSONArray();
                            for (KeyWords keyWords : keyList) {
                                JSONObject jo = new JSONObject();
                                jo.put("kid", keyWords.getKey_words_id());
                                jo.put("key", keyWords.getKey_word());
                                keyArray.add(jo);
                            }
                            detailObject.put("keyList", keyArray);
                            //List<CartHasImages> chiList = cdi.getRattingList(Integer.parseInt(imgid));

                            String sql = "SELECT * FROM images WHERE categories_category_id='"
                                    + img.getCategories_category_id() + "' AND image_state_image_state_id='1'";
                            PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql);
                            ResultSet rs = ps.executeQuery();
                            JSONArray simImage = new JSONArray();
                            while (rs.next()) {
                                JSONObject jo = new JSONObject();
                                jo.put("simid", rs.getInt(1));
                                jo.put("url", rs.getString(15));
                                simImage.add(jo);
                            }
                            detailObject.put("imgList", simImage);
                            System.out.println("user id " + uid);
                            if (Integer.parseInt(uid) != (-1) && Integer.parseInt(uid) != 0) {
                                Cart cct = cdi.getCart(Integer.parseInt(uid));
                                if (cct != null) {
                                    boolean have = cdi.isThisInLightBoxImage(cct.getCart_id(), 2,
                                            Integer.parseInt(imgid));
                                    if (have) {
                                        detailObject.put("lightbox", 1);
                                    } else {
                                        detailObject.put("lightbox", 0);
                                    }
                                } else {
                                    detailObject.put("lightbox", 0);
                                }
                            } else {
                                detailObject.put("lightbox", 0);
                            }
                            out.write("json=" + detailObject.toJSONString());
                        }
                    } else {
                        out.write("msg=Unable to complete the action.Please try again later.");
                    }
                } else {
                    out.write("msg=Internal server error,Please try again later.");
                }
            } else if (type.equals("lightbox")) {

                String imgid = request.getParameter("imgid");
                String uid = request.getParameter("uid");

                System.out.println(imgid);
                System.out.println(uid);

                ImagesSub is = null;
                Credits cre = null;
                Cart cart = null;

                is = idip.getLowestQuality(Integer.parseInt(imgid));
                cre = new CreditsDAOImp().getCreditDetails(is.getCredits());
                cart = new CartDAOImp().getCart(Integer.parseInt(uid));
                System.gc();
                if (is != null) {
                    boolean ok = new CartDAOImp().addToLightBox(Integer.parseInt(imgid), is.getSub_images_id(),
                            2, cart.getCart_id(), date, cre.getCredits());
                    if (ok) {
                        out.write("msg=Successfully_add_lightbox");
                    } else {
                        out.write("msg=Unable to complete the action,Please try again later.");

                    }

                } else {
                    out.write("msg=Internal server error,Please try again later.");

                }
            } else if (type.equals("Add_cart")) {
                String imgid = request.getParameter("imgid");
                String sid = request.getParameter("sid");
                String uid = request.getParameter("uid");

                System.out.println(imgid);
                System.out.println(sid);
                System.out.println(uid);

                Images img = idip.getImageDetail(Integer.parseInt(imgid));
                boolean update = false;
                boolean o = false;

                if (img != null) {
                    int i = 0;
                    int subimg_Id = Integer.parseInt(sid);
                    ImagesSub isu = idip.getSubImage(subimg_Id);

                    if (isu != null) {

                        CreditsDAOImp cdi = new CreditsDAOImp();

                        int credits = cdi.getCredit(isu.getCredits());

                        CartItems ci = null;

                        int cartCount = 0;

                        if (uid == null) {

                        } else {
                            //if user signin
                            System.out.println("signIn user");
                            //          

                            List<CartItems> citems;

                            Cart b = new CartDAOImp().getCart(Integer.parseInt(uid));
                            //           
                            //           System.out.println("cart :"+b.getCart_id());
                            //           System.out.println("cart is null"+b==null);
                            //           
                            if (b.getCart_id() == 0) {

                                //if user didn't have cart in the database
                                System.out.println("don't have a cart");
                                Cart c = new Cart();
                                c.setUser_id(Integer.parseInt(uid));
                                c.setCredit_count(0);
                                c.setCredit_unit_price_id(1);
                                c.setImage_count(0);
                                c.setSubscription_unit_price_id(1);

                                //creating a new cart
                                boolean bb = new CartDAOImp().setACart(c);
                                System.out.println("created a new cart" + bb);
                                System.gc();

                                if (bb) {
                                    //getting that new cart 

                                    b = new CartDAOImp().getCart(Integer.parseInt(uid));

                                    if (b == null) {

                                    } else {
                                        CartItems cartI = new CartItems();
                                        cartI.setImgId(Integer.parseInt(imgid));
                                        cartI.setSubimg_Id(subimg_Id);
                                        cartI.setCredit(credits);
                                        cartI.setDate(date);

                                        boolean owner = idip.checkOwner(Integer.parseInt(uid),
                                                Integer.parseInt(imgid));
                                        if (owner) {
                                            out.write("msg=This is your image,you can't add to cart.");

                                        } else {
                                            //  boolean alreadyPur=new CartDAOImp().checkAlreadyPurchase(b.getCart_id(),cartI.getImgId());
                                            //if(!alreadyPur){ 
                                            boolean duplicat = new CartDAOImp()
                                                    .checkImageDuplication(b.getCart_id(), cartI.getImgId());
                                            if (duplicat) {
                                                boolean updated = new CartDAOImp()
                                                        .updateCartHasImagesSubImageID(b.getCart_id(),
                                                                cartI.getImgId(), cartI.getSubimg_Id(),
                                                                cartI.getCredit());
                                            } else {
                                                System.out.println("addingCarItems");
                                                o = new CartDAOImp().addingCarItems(cartI, b);
                                                System.gc();

                                            }

                                        }
                                    }

                                }
                                System.gc();
                            } else {
                                //if user have a cart in the database

                                System.out.println("this user have a car in the DB");
                                b = new CartDAOImp().getCart(Integer.parseInt(uid));

                                List<CartHasImages> ch = null;

                                int imgcount = 0;
                                int creditcount = 0;

                                if (b == null) {

                                } else {
                                    //               
                                    CartItems cartI = new CartItems();
                                    cartI.setImgId(Integer.parseInt(imgid));
                                    cartI.setSubimg_Id(subimg_Id);
                                    cartI.setCredit(credits);
                                    cartI.setDate(date);

                                    boolean owner = idip.checkOwner(Integer.parseInt(uid),
                                            Integer.parseInt(imgid));
                                    if (owner) {
                                        out.write("msg=This is your image,you can't add to cart.");
                                    } else {

                                        boolean duplicat = new CartDAOImp()
                                                .checkImageDuplication(b.getCart_id(), cartI.getImgId());
                                        if (duplicat) {
                                            boolean updated = new CartDAOImp().updateCartHasImagesSubImageID(
                                                    b.getCart_id(), cartI.getImgId(), cartI.getSubimg_Id(),
                                                    cartI.getCredit());
                                            out.write("msg=Image is added to the cart.");
                                        } else {
                                            System.out.println("addingCarItems");
                                            o = new CartDAOImp().addingCarItems(cartI, b);
                                            System.gc();
                                            out.write("msg=Image is added to the cart.");

                                        }

                                    }
                                    ch = new CartDAOImp().listCartHasImages();
                                    for (CartHasImages carhi : ch) {

                                        if (carhi.getCart_id() == b.getCart_id()
                                                && carhi.getIs_purchase() == 0) {
                                            imgcount++;
                                            creditcount += carhi.getCredits();
                                            System.out.println(
                                                    "-----------------totalcount------------------------"
                                                            + imgcount);
                                            System.out
                                                    .println("-----------------credits------------------------"
                                                            + creditcount);
                                        }

                                    }
                                    update = new CartDAOImp().updateCartQty(imgcount, creditcount,
                                            b.getCart_id());

                                }
                                //               
                                System.gc();
                            }
                        }

                        System.out.println("near end");

                        //                            System.gc();
                        //                            response.sendRedirect("description.jsp?image_id=" + imgid);

                    } else {

                        out.write("msg=Internal server error,Please try again later.");
                    }

                } else {
                    out.write("msg=Internal server error,Please try again later.");
                }

            }
        } else {
            out.write("msg=Internal server error,Please try again later.");
        }

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

}

From source file:org.openbmap.soapclient.ExportSessionTask.java

/**
 * Builds cell xml files and saves/uploads them
 *///from   w  ww.ja  va 2  s  .c om
@SuppressLint("NewApi")
@Override
protected final Boolean doInBackground(final Void... params) {
    ArrayList<String> wifiFiles = new ArrayList<>();
    ArrayList<String> cellFiles = new ArrayList<>();
    Boolean success = true;

    if (!mSkipUpload && mAnonymousUpload && (mExportCells || mExportWifis)) {
        mToken = getToken();
        Log.i(TAG, "Token " + mToken);
    }

    if (mExportCells) {
        Log.i(TAG, "Exporting cells");
        // export cells
        publishProgress(mAppContext.getResources().getString(R.string.please_stay_patient),
                mAppContext.getResources().getString(R.string.exporting_cells), 0);
        cellFiles = new CellSerializer(mAppContext, mSession, mTempPath, RadioBeacon.SW_VERSION).export();

        // upload
        if (!mSkipUpload) {
            uploadAllCells(cellFiles);
        }
    } else {
        Log.i(TAG, "Cell export skipped");
    }

    if (mExportWifis) {
        Log.i(TAG, "Exporting wifis");
        // export wifis
        publishProgress(mAppContext.getResources().getString(R.string.please_stay_patient),
                mAppContext.getResources().getString(R.string.exporting_wifis), 50);
        wifiFiles = new WifiSerializer(mAppContext, mSession, mTempPath, RadioBeacon.SW_VERSION, mAnonymiseSsid)
                .export();

        // upload
        if (!mSkipUpload) {
            uploadAllWifis(wifiFiles);
        }
    } else {
        Log.i(TAG, "Wifi export skipped");
    }

    if (!mSkipUpload) {
        // wait max 30s for all upload tasks to finish
        final long startGrace = System.currentTimeMillis();
        sleepTillCompleted(startGrace);

        // check, whether all files are uploaded
        if (mUploadedFiles.size() != (wifiFiles.size() + cellFiles.size())) {
            Log.e(TAG, "Not all files have been uploaded!");
            // set state to failed on upload problems
            success = false;
        } else {
            Log.i(TAG, "All files uploaded");
        }

        // and cleanup
        if (!mKeepXml) {
            // delete only successfully uploaded files
            Log.i(TAG, "Deleting uploaded files");
            deleteXmlFiles(mUploadedFiles);
        } else {
            Log.i(TAG, "Deleting files skipped");
        }
    }
    // clean up a bit
    wifiFiles = null;
    cellFiles = null;
    mUploadedFiles = null;
    System.gc();

    if (mUpdateWifiCatalog) {
        Log.i(TAG, "Updating wifi catalog");
        new CatalogUpdater(mAppContext).execute((Void[]) null);
    }

    if (mSaveGpx) {
        Log.i(TAG, "Exporting gpx");
        publishProgress(mAppContext.getResources().getString(R.string.please_stay_patient),
                mAppContext.getResources().getString(R.string.exporting_gpx), 75);

        final String filename = GpxSerializer.suggestGpxFilename(mSession);
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mAppContext);
        final int verbosity = Integer
                .parseInt(prefs.getString(Preferences.KEY_GPX_VERBOSITY, Preferences.VAL_GPX_VERBOSITY));

        final SaveGpxTask task = new SaveGpxTask(mAppContext, null, mSession, mTempPath, filename, verbosity);
        task.execute();
    } else {
        Log.i(TAG, "GPX export skipped");
    }

    return success;
}

From source file:net.pms.external.ExternalFactory.java

private static void purgeCode(String mainClass, URL newUrl) {
    Class<?> clazz1 = null;

    for (Class<?> clazz : externalListenerClasses) {
        if (mainClass.equals(clazz.getCanonicalName())) {
            clazz1 = clazz;//w w  w .j a v  a2s . com
            break;
        }
    }

    if (clazz1 == null) {
        return;
    }

    externalListenerClasses.remove(clazz1);
    ExternalListener remove = null;
    for (ExternalListener list : externalListeners) {
        if (list.getClass().equals(clazz1)) {
            remove = list;
            break;
        }
    }

    RendererConfiguration.resetAllRenderers();

    if (remove != null) {
        externalListeners.remove(remove);
        remove.shutdown();
        LooksFrame frame = (LooksFrame) PMS.get().getFrame();
        frame.getPt().removePlugin(remove);
    }

    for (int i = 0; i < 3; i++) {
        System.gc();
    }

    URLClassLoader cl = (URLClassLoader) clazz1.getClassLoader();
    URL[] urls = cl.getURLs();
    for (URL url : urls) {
        String mainClass1 = getMainClass(url);

        if (mainClass1 == null || !mainClass.equals(mainClass1)) {
            continue;
        }

        File f = url2file(url);
        File f1 = url2file(newUrl);

        if (f1 == null || f == null) {
            continue;
        }

        if (!f1.getName().equals(f.getName())) {
            addToPurgeFile(f);
        }
    }
}

From source file:eu.planets_project.pp.plato.application.AdminAction.java

public String cleanupValues() {
    List<PlanProperties> ppList = em.createQuery("select p from PlanProperties p").getResultList();
    int total = 0;
    int i = 0;/*  w  ww  . j a v a 2  s .c  o m*/
    for (PlanProperties pp : ppList) {
        int number = projectCleaner.cleanupProject(pp.getId());
        FacesMessages.instance().add(FacesMessage.SEVERITY_INFO,
                "Plan " + pp.getName() + ": removed " + number + " values.");
        total += number;
        i++;
        if ((i % 5) == 0) {
            System.gc();
        }
    }
    FacesMessages.instance().add(FacesMessage.SEVERITY_INFO,
            "All projects cleaned up, removed " + total + " Values objects in total");
    return null;
}

From source file:ch.algotrader.starter.SimulationStarter.java

private static void runSimulation(final BiConsumer<SimulationExecutor, StrategyGroup> consumer) {
    final ServiceLocator serviceLocator = ServiceLocator.instance();
    serviceLocator.init(ServiceLocator.SIMULATION_BEAN_REFERENCE_LOCATION);
    try {/*from  w  w w. ja v a2  s  .  c om*/
        StrategyGroup strategyGroup;
        if (serviceLocator.getContext().containsBean("strategyGroup")) {
            strategyGroup = serviceLocator.getContext().getBean("strategyGroup", StrategyGroup.class);
        } else {
            final ConfigParams configParams = ConfigLocator.instance().getConfigParams();
            strategyGroup = StrategyGroup.single(configParams.getString("strategyName"));
        }
        SimulationExecutor executor = serviceLocator.getService("simulationExecutor", SimulationExecutor.class);
        consumer.accept(executor, strategyGroup);

    } finally {
        serviceLocator.shutdown();
    }
    // run a garbage collection
    System.gc();
}