List of usage examples for java.lang System gc
public static void gc()
From source file:hu.bme.mit.sette.tools.jpet.JPetRunner.java
@Override public void cleanUp() throws IOException { // TODO better search for (Integer pid : ProcessUtils.searchProcess("jpet/pet")) { System.err.println(" Terminating stuck process (PID: " + pid + ")"); try {//from www . java 2 s . com ProcessUtils.terminateProcess(pid); } catch (Exception e) { System.err.println(" Exception"); e.printStackTrace(); } } System.gc(); }
From source file:com.quix.aia.cn.imo.rest.AddressBookRest.java
/** * <p>/*from w ww. j a v a 2 s . com*/ * Address Book Synchronization rest service post method which gets Json * string, which contains list of Address Book records. This method performs * save or update operations. It returns Json string with local address code * with IOS address code. * </p> * * @param jsonAddressBookListString * */ @POST @Path("/sync") @Consumes(MediaType.TEXT_PLAIN) @Produces({ MediaType.APPLICATION_JSON }) public Response syncAddressBook(String jsonAddressBookListString) { log.log(Level.INFO, "Address Book --> Sync Record "); log.log(Level.INFO, "Address Book --> Sync Record --> Data for Sync... ::::: " + jsonAddressBookListString); MsgBeans beans = new MsgBeans(); AuditTrailMaintenance auditTrailMaint = new AuditTrailMaintenance(); List<AddressBook> jsonObjList = new ArrayList(); GsonBuilder builder = new GsonBuilder(); AddressBookMaintenance addressBookMaintenance = new AddressBookMaintenance(); Gson googleJson = null; Type listType = null; String returnJsonString = ""; try { returnJsonString = "["; builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Date date = LMSUtil.convertDateToyyyymmddhhmmssDashed(json.getAsString()); if (null != date) { return date; } else { return LMSUtil.convertDateToyyyy_mm_dd(json.getAsString()); } } }); builder.registerTypeHierarchyAdapter(byte[].class, new JsonDeserializer<byte[]>() { public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return Base64.decodeBase64(json.getAsString()); } }); googleJson = builder.create(); listType = new TypeToken<List<AddressBook>>() { }.getType(); jsonObjList = googleJson.fromJson(jsonAddressBookListString, listType); // maintain in single transaction returnJsonString += addressBookMaintenance.insertOrUpdateRestBatch(jsonObjList); returnJsonString += "]"; log.log(Level.INFO, "Address Book --> saved successfully "); auditTrailMaint.insertAuditTrail( new AuditTrail("Rest", AuditTrail.MODULE_ADDRESS_BOOK, AuditTrail.FUNCTION_SUCCESS, "SUCCESS")); return Response.status(200).entity(returnJsonString).build(); } catch (Exception e) { beans.setCode("500"); beans.setMassage( "Something wrong happens, please contact administrator. Error Message : " + e.getMessage()); auditTrailMaint.insertAuditTrail( new AuditTrail("Rest", AuditTrail.MODULE_ADDRESS_BOOK, AuditTrail.FUNCTION_FAIL, "FAILED")); log.log(Level.SEVERE, "Address Book --> Error in Save Record."); log.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); LogsMaintenance logsMain = new LogsMaintenance(); logsMain.insertLogs("AddressBookRest", Level.SEVERE + "", errors.toString()); return Response.status(200).entity(googleJson.toJson(beans)).build(); } finally { jsonObjList.clear(); auditTrailMaint = null; addressBookMaintenance = null; builder = null; googleJson = null; listType = null; returnJsonString = null; beans = null; System.gc(); } }
From source file:eu.betaas.taas.contextmanager.onto.classesExt.wordnet.WordNetUtils.java
public boolean init() { String[] includedWordnetFiles = null; boolean bCorrect = true; try {/* w w w . j av a 2s . c om*/ mLogger.debug( "Component CM perform operation WordNetUtils.checkWordnet. This is a wrapper for the MIT WordNet inteface that simplifies basic operations such as retrieving synonyms for a word."); File fileDestiny = null; String pathWordnetFileName = null; if (isLinux()) { WORDNET = WORDNET_LINUX; } else if (isWindows()) { WORDNET = WORDNET_WIN; } else mLogger.error("ERROR, unknown SO"); PREFIX_WORDNET = "/META-INF/" + WORDNET + "/"; File pathWordnetDirectory = new File(tmpdir1, WORDNET); if (!pathWordnetDirectory.exists() && !pathWordnetDirectory.mkdir()) throw new IOException("Failed to create temporary directory " + pathWordnetDirectory); if (isLinux()) { includedWordnetFiles = new String[] { PREFIX_WORDNET + "adj.exc", PREFIX_WORDNET + "adv.exc", PREFIX_WORDNET + "cntlist", PREFIX_WORDNET + "cntlist.rev", PREFIX_WORDNET + "data.adj", PREFIX_WORDNET + "data.adv", PREFIX_WORDNET + "data.noun", PREFIX_WORDNET + "data.verb", PREFIX_WORDNET + "frames.vrb", PREFIX_WORDNET + "index.verb", PREFIX_WORDNET + "index.adj", PREFIX_WORDNET + "index.adv", PREFIX_WORDNET + "index.noun", PREFIX_WORDNET + "index.sense", PREFIX_WORDNET + "lexnames", PREFIX_WORDNET + "log.grind.3.0", PREFIX_WORDNET + "Makefile", PREFIX_WORDNET + "Makefile.am", PREFIX_WORDNET + "Makefile.in", PREFIX_WORDNET + "noun.exc", PREFIX_WORDNET + "sentidx.vrb", PREFIX_WORDNET + "sents.vrb", PREFIX_WORDNET + "verb.exc", PREFIX_WORDNET + "verb.Framestext" }; } else if (isWindows()) { includedWordnetFiles = new String[] { PREFIX_WORDNET + "adj.exc", PREFIX_WORDNET + "adv.exc", PREFIX_WORDNET + "cntlist", PREFIX_WORDNET + "cntlist.rev", PREFIX_WORDNET + "data.adj", PREFIX_WORDNET + "data.adv", PREFIX_WORDNET + "data.noun", PREFIX_WORDNET + "data.verb", PREFIX_WORDNET + "frames.vrb", PREFIX_WORDNET + "index.verb", PREFIX_WORDNET + "index.adj", PREFIX_WORDNET + "index.adv", PREFIX_WORDNET + "index.noun", PREFIX_WORDNET + "index.sense", PREFIX_WORDNET + "log.grind.2.1", PREFIX_WORDNET + "noun.exc", PREFIX_WORDNET + "sentidx.vrb", PREFIX_WORDNET + "sents.vrb", PREFIX_WORDNET + "verb.exc", PREFIX_WORDNET + "verb.Framestext" }; } else mLogger.error("Your OS is not support!!"); ClassLoader wordnetClassLoader = WordNetUtils.class.getClassLoader(); for (String includedWordnetFile : includedWordnetFiles) { URL urlSource = wordnetClassLoader.getResource(includedWordnetFile); InputStream isSource = this.getClass().getResourceAsStream(includedWordnetFile); if (urlSource != null) { try { String pathWordnetFile = urlSource.toString(); pathWordnetFileName = pathWordnetFile.substring(pathWordnetFile.lastIndexOf("/") + 1); fileDestiny = new File(tmpdir1, "/" + WORDNET + "/" + pathWordnetFileName); fileDestiny.deleteOnExit(); FileUtils.copyInputStreamToFile(isSource, fileDestiny); isSource.close(); } catch (Exception e) { bCorrect = false; mLogger.error( "Component CM perform operation WordNetUtils.checkWordnet. It has not been executed correctly. Problems with copy InputStream to File. Exception: " + e.getMessage() + "."); } finally { isSource.close(); IOUtils.closeQuietly(isSource); isSource = null; System.gc(); } } } } catch (Exception e) { mLogger.error( "Component CM perform operation WordNetUtils.checkWordnet. It has not been executed correctly. Exception: " + e.getMessage() + "."); } return bCorrect; }
From source file:dk.statsbiblioteket.util.reader.ReplacerTest.java
@Test @Ignore//from w ww . ja v a 2s . c o m public void testSpeedCharVsChars() throws Exception { Random random = new Random(456); int RUNS = 10; int[] RULES = new int[] { 0, 10, 100, 1000 }; int[] INPUT_CHARS = new int[] { 10, 100, 1000, 10000, 1000000, 10000000 }; for (int ruleCount : RULES) { for (int inputChars : INPUT_CHARS) { Map<String, String> rules = ReplacePerformanceTest.getRangeReplacements(ruleCount, 1, 1, 1, 1); String input = ReplacePerformanceTest.randomWord(random, 0, inputChars); TextTransformer charT = new CharReplacer(rules); TextTransformer charsT = new CharArrayReplacer(rules); System.gc(); long charTime = 0; long charsTime = 0; for (int runs = 0; runs < RUNS; runs++) { long startTime = System.currentTimeMillis(); charT.transform(input); charTime += System.currentTimeMillis() - startTime; startTime = System.currentTimeMillis(); charsT.transform(input); charsTime += System.currentTimeMillis() - startTime; } log.info("Rules: " + rules.size() + ", input length: " + input.length() + ", char: " + charTime / RUNS + "ms, chars: " + charsTime / RUNS + "ms"); } } }
From source file:eu.planets_project.pp.plato.application.AdminAction.java
/** * Adds a news entry to list of messages displayed to user. * @see #allmessages/*from w w w . j a v a2s . c om*/ */ public void addNews() { if (check()) { allmessages.addNewsMessage(new NewsClass(news, importance, author)); news = ""; } System.gc(); }
From source file:eu.scape_project.planning.xml.ProjectExportAction.java
/** * Exports the project identified by PlanProperties.Id ppid and writes the * document to the given OutputStream - including all binary data. * (currently required by {@link #exportAllProjectsToZip()} ) - Does NOT * clean up temp files written to baseTempPath * //from w w w .ja v a 2 s. c om * @param ppid * @param out * @param baseTempPath * used to write temp files for binary data, must not be used by * other exports at the same time * @return True if export was successful, false otherwise. */ public boolean exportComplete(int ppid, OutputStream out, String baseTempPath) { ProjectExporter exporter = new ProjectExporter(); Document doc = exporter.createProjectDoc(); Plan plan = null; try { plan = em.createQuery("select p from Plan p where p.planProperties.id = :ppid ", Plan.class) .setParameter("ppid", ppid).getSingleResult(); } catch (Exception e) { log.error("Could not load planProperties: ", e); log.debug("Skipping the export of the plan with properties " + ppid + ": Couldnt load."); return false; } try { String tempPath = baseTempPath; File tempDir = new File(tempPath); tempDir.mkdirs(); try { exporter.addProject(plan, doc, false); // Perform XSLT transformation to get the DATA into the PLANS // Prepare base 64 encoded binary data List<Integer> binaryObjectIds = getBinaryObjectIds(doc); writeBinaryObjects(binaryObjectIds, tempPath); // Prepare preservation action plan List<Integer> preservationActionPlanIDs = getPreservationActionPlanIds(doc); writeDigitalObjects(preservationActionPlanIDs, tempPath); // Call XSLT addBinaryData(doc, out, tempPath); } catch (IOException e) { log.error("Could not open outputstream.", e); return false; } catch (TransformerException e) { log.error("failed to generate export file.", e); return false; } catch (StorageException e) { log.error("Could not load object from stoarge.", e); return false; } catch (PlanningException e) { log.error("Could not export plan.", e); return false; } } finally { // Clean up plan = null; em.clear(); System.gc(); } return true; }
From source file:com.norconex.commons.lang.file.FileUtil.java
/** * Deletes a file or a directory recursively in a more robust way. * This method applies the following strategies: * <ul>//from w w w . j av a 2s. c o m * <li>If file or directory deletion does not work, it will re-try 10 * times, waiting 1 second between each try to give a chance to * whatever OS lock on the file to go.</li> * <li>After a first failed attempt, it invokes {@link System#gc()} * in hope of releasing any handles left on files. This is in * relation to a known Java bug mostly occurring on Windows * (<a href="http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4715154" * >http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4715154</a>).</li> * <li>It throws a IOException if the delete still fails after the 10 * attempts (as opposed to fail silently).</li> * <li>If file is <code>null</code> or does not exist, nothing happens. * </ul> * @param file file or directory to delete * @throws IOException cannot delete file. * @since 1.4. Renamed from <code>deleteFile(File)</code> */ public static void delete(File file) throws IOException { if (file == null || !file.exists()) { return; } boolean success = false; int failure = 0; while (!success && failure < MAX_FILE_OPERATION_ATTEMPTS) { if (file.exists() && !FileUtils.deleteQuietly(file)) { failure++; System.gc(); Sleeper.sleepSeconds(1); continue; } success = true; } if (!success) { throw new IOException("Could not delete \"" + file + "\"."); } }
From source file:com.couchbase.lite.LiteTestCaseWithDB.java
protected Context getTestContext(String dirName, boolean deleteContent) { Context context = getTestContext(dirName); if (deleteContent && context.getFilesDir().exists()) { // NOTE: retry and sleep is only for Windows. Other platforms never fail. int counter = 0; while (!FileDirUtils.cleanDirectory(context.getFilesDir()) && counter < 10) { // NOTE: forestdb releses resources in Object.destroy() System.gc(); try { Thread.sleep(1000); } catch (Exception e) { }//www.j a va 2 s . c o m counter++; } assertTrue(counter < 10); } return context; }
From source file:org.pf.midea.SimulationController.java
@Override public void run() { textAreaNumeric.setText(""); XYSeriesCollection xySeriesCollection = new XYSeriesCollection(); double progress = 0; double progressStep = 100.0 / (planCells.length * (hSquareHigh - hSquareLow + hSquareStep) / hSquareStep); progressBar.setValue(0);// w w w . j av a2 s . c o m for (int i = 0; i < planCells.length; i++) { XYSeries xySeries; if (showLineNumbers) xySeries = new XYSeries(String.valueOf(i + 1) + ") " + planCells[i].getShortDescription()); else xySeries = new XYSeries(planCells[i].getShortDescription()); textAreaNumeric.append(planCells[i].getDescription() + "\n"); textAreaNumeric.setCaretPosition(textAreaNumeric.getDocument().getLength()); PlanStates.SourceType currentSourceType = planCells[i].getSourceCell().getSourceType(); PlanStates.CodeType currentCodeType = planCells[i].getCodeCell().getCodeType(); PlanStates.ModulationType currentModulationType = planCells[i].getModulationCell().getModulationType(); PlanStates.ChannelType currentChannelType = planCells[i].getChannelCell().getChannelType(); PlanStates.ErrorsType currentErrorsType = planCells[i].getErrorsCell().getErrorsType(); BinaryNumber[] sourcePoints = null; switch (currentSourceType) { case ST_TEST: sourcePoints = ConstellationPointsGenerator.getTestPoints(currentModulationType, iterationsCount); break; case ST_RANDOM: sourcePoints = ConstellationPointsGenerator.getRandomPoints(currentModulationType, iterationsCount); break; } Coder coder = null; Decoder decoder = null; switch (currentCodeType) { case CT_NONE: coder = new CoderNone(); decoder = new DecoderNone(); break; case CT_HAMMING74: coder = new CoderHamming74(); decoder = new DecoderHamming74(); break; case CT_CYCLIC: coder = new CoderCyclic85(); decoder = new DecoderCyclic85(); break; case CT_BCH155: coder = new CoderBCH155(); decoder = new DecoderBCH155(); break; } Modulator modulator = null; Demodulator demodulator = null; switch (currentModulationType) { case MT_ASK: modulator = new ModulatorASK(); demodulator = new DemodulatorASK(); break; case MT_FSK: modulator = new ModulatorFSK(); demodulator = new DemodulatorFSK(); break; case MT_BPSK: modulator = new ModulatorBPSK(); demodulator = new DemodulatorBPSK(); break; case MT_QPSK: modulator = new ModulatorQPSK(); demodulator = new DemodulatorQPSK(); break; case MT_8PSK: modulator = new Modulator8PSK(); demodulator = new Demodulator8PSK(); break; case MT_16PSK: modulator = new Modulator16PSK(); demodulator = new Demodulator16PSK(); break; case MT_32PSK: modulator = new Modulator32PSK(); demodulator = new Demodulator32PSK(); break; case MT_16QAM: modulator = new Modulator16QAM(); demodulator = new Demodulator16QAM(); break; case MT_32QAM: modulator = new Modulator32QAM(); demodulator = new Demodulator32QAM(); break; case MT_64QAM: modulator = new Modulator64QAM(); demodulator = new Demodulator64QAM(); break; case MT_256QAM: modulator = new Modulator256QAM(); demodulator = new Demodulator256QAM(); break; } Channel channel = null; switch (currentChannelType) { case CHT_AWGN: channel = new ChannelAWGN(); break; case CHT_RAYLEIGH: channel = new ChannelRayleigh(); break; } BinaryNumber[] encoded = coder.encode(sourcePoints); Signal[] modulated = modulator.modulate(encoded); double error = 0; for (double h = hSquareLow; h <= hSquareHigh; h += hSquareStep) { double realH; if (dBs) realH = StatisticsTools.decibelsToTimes(h); else realH = h; Signal[] noised = channel.noise(realH, modulated); BinaryNumber[] demodulated = demodulator.demodulate(noised); noised = null; System.gc(); BinaryNumber[] decoded = decoder.decode(demodulated); demodulated = null; System.gc(); switch (currentErrorsType) { case ET_SER: error = StatisticsTools.getSER(sourcePoints, decoded); break; case ET_BER: error = StatisticsTools.getBER(sourcePoints, decoded); break; } decoded = null; System.gc(); if (error > 0) { xySeries.add(h, error); textAreaNumeric.append(String.valueOf(h) + "\t" + String.valueOf(error) + "\n"); textAreaNumeric.setCaretPosition(textAreaNumeric.getDocument().getLength()); } progress += progressStep; progressBar.setValue((int) Math.round(progress)); } xySeriesCollection.addSeries(xySeries); textAreaNumeric.append("\n"); textAreaNumeric.setCaretPosition(textAreaNumeric.getDocument().getLength()); } JFreeChart chart = ChartFactory.createXYLineChart("", dBs ? "" : "", "?", xySeriesCollection, PlotOrientation.VERTICAL, true, true, false); chart.getLegend().setPosition(RectangleEdge.RIGHT); XYPlot xyPlot = chart.getXYPlot(); for (int i = 0; i < planCells.length; i++) { xyPlot.getRenderer().setSeriesStroke(i, new BasicStroke(planCells[i].getLineWidth())); if (planCells[i].getLineColor() != null) xyPlot.getRenderer().setSeriesPaint(i, planCells[i].getLineColor()); if (showLineNumbers) { XYSeries currentSeries = xySeriesCollection.getSeries(i); double annotationY = currentSeries.getY(0).doubleValue(); double annotationX = currentSeries.getX(0).doubleValue(); for (int j = 1; j < currentSeries.getItemCount(); j++) if (currentSeries.getY(j).doubleValue() == 0) { annotationY = currentSeries.getY(j - 1).doubleValue(); annotationX = currentSeries.getX(j - 1).doubleValue(); break; } else { annotationY = currentSeries.getY(j).doubleValue(); annotationX = currentSeries.getX(j).doubleValue(); } XYTextAnnotation annotation = new XYTextAnnotation(String.valueOf(i + 1), annotationX, annotationY); annotation.setBackgroundPaint(Color.WHITE); annotation.setFont(new Font("Dialog", 0, 14)); xyPlot.addAnnotation(annotation); } } xyPlot.setBackgroundPaint(Color.WHITE); xyPlot.setDomainGridlinePaint(Color.GRAY); xyPlot.setRangeGridlinePaint(Color.GRAY); NumberAxis domainAxis = new NumberAxis("h, " + (dBs ? "" : "")); LogAxis rangeAxis = new LogAxis("?"); rangeAxis.setNumberFormatOverride(new HumanNumberFormat(1)); domainAxis.setTickLabelFont(new Font("Dialog", 0, 14)); rangeAxis.setTickLabelFont(new Font("Dialog", 0, 14)); xyPlot.setDomainAxis(domainAxis); xyPlot.setRangeAxis(rangeAxis); ChartPanel nestedPanel = new ChartPanel(chart); chartPanel.removeAll(); chartPanel.add(nestedPanel, new CellConstraints()); chartPanel.updateUI(); }
From source file:CB_Core.Api.PocketQuery.java
/** * @param AccessToken/*w ww .ja v a 2 s . c o m*/ * Config.GetAccessToken(true) * @param pocketQueryConfig * Config.settings.PocketQueryFolder.getValue() * @param PqFolder * @return */ public static int DownloadSinglePocketQuery(PQ pocketQuery, String PqFolder) { HttpGet httpGet = new HttpGet( GroundspeakAPI.GS_LIVE_URL + "GetPocketQueryZippedFile?format=json&AccessToken=" + GroundspeakAPI.GetAccessToken(true) + "&PocketQueryGuid=" + pocketQuery.GUID); try { // String result = GroundspeakAPI.Execute(httpGet); httpGet.setHeader("Accept", "application/json"); httpGet.setHeader("Content-type", "application/json"); // Execute HTTP Post Request String result = ""; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpGet); int buffLen = 32 * 1024; byte[] buff = new byte[buffLen]; InputStream inputStream = response.getEntity().getContent(); int buffCount = inputStream.read(buff, 0, buffLen); int buffPos = 0; result = ""; // now read from the response until the ZIP Informations are beginning or to the end of stream for (int i = 0; i < buffCount; i++) { byte c = buff[i]; result += (char) c; if (result.contains("\"ZippedFile\":\"")) { // The stream position represents the beginning of the ZIP block // to have a correct JSON Array we must add a "}} to the // result result += "\"}}"; buffPos = i; // Position im Buffer, an der die ZIP-Infos beginnen break; } } // try // Parse JSON Result { JSONTokener tokener = new JSONTokener(result); JSONObject json = (JSONObject) tokener.nextValue(); JSONObject status = json.getJSONObject("Status"); if (status.getInt("StatusCode") == 0) { GroundspeakAPI.LastAPIError = ""; SimpleDateFormat postFormater = new SimpleDateFormat("yyyyMMddHHmmss"); String dateString = postFormater.format(pocketQuery.DateLastGenerated); String local = PqFolder + "/" + pocketQuery.Name + "_" + dateString + ".zip"; // String test = json.getString("ZippedFile"); FileOutputStream fs; fs = new FileOutputStream(local); BufferedOutputStream bfs = new BufferedOutputStream(fs); try { // int firstZipPos = result.indexOf("\"ZippedFile\":\"") + 14; // int lastZipPos = result.indexOf("\"", firstZipPos + 1) - 1; CB_Utils.Converter.Base64.decodeStreamToStream(inputStream, buff, buffLen, buffCount, buffPos, bfs); } catch (Exception ex) { } // fs.write(resultByte); bfs.flush(); bfs.close(); fs.close(); result = null; System.gc(); return 0; } else { GroundspeakAPI.LastAPIError = ""; GroundspeakAPI.LastAPIError = "StatusCode = " + status.getInt("StatusCode") + "\n"; GroundspeakAPI.LastAPIError += status.getString("StatusMessage") + "\n"; GroundspeakAPI.LastAPIError += status.getString("ExceptionDetails"); return (-1); } } catch (JSONException e) { e.printStackTrace(); } } catch (ClientProtocolException e) { System.out.println(e.getMessage()); return (-1); } catch (IOException e) { System.out.println(e.getMessage()); return (-1); } return 0; }