List of usage examples for java.lang System gc
public static void gc()
From source file:edu.harvard.i2b2.eclipse.plugins.metadataLoader.ws.OntServiceDriver.java
public static String sendREST(EndpointReference restEPR, String requestString, String type) throws Exception { // requestString.replaceAll("\\p{Cntrl}", ""); did not fix illegal control char error OMElement getOnt = getOntPayLoad(requestString); MessageUtil.getInstance().setNavRequest("URL: " + restEPR + "\n" + getOnt.toString()); Options options = new Options(); log.debug(restEPR.toString());// w w w . j a v a 2 s . c o m options.setTo(restEPR); options.setTransportInProtocol(Constants.TRANSPORT_HTTP); options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(125000)); options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, new Integer(125000)); ServiceClient sender = OntServiceClient.getServiceClient(); sender.setOptions(options); OMElement result; try { result = sender.sendReceive(getOnt); } catch (java.lang.OutOfMemoryError e) { System.gc(); throw new I2B2Exception("Out of memory"); // return null; } String response = result.toString(); MessageUtil.getInstance().setNavResponse("URL: " + restEPR + "\n" + response); return response; }
From source file:de.blizzy.backup.restore.RestoreDialog.java
@Override public boolean close() { IRunnableWithProgress runnable = new IRunnableWithProgress() { @Override//w ww. j a v a 2 s. c om public void run(IProgressMonitor monitor) { monitor.beginTask(Messages.Title_CloseBackupDatabase, IProgressMonitor.UNKNOWN); try { database.close(); for (final IStorageInterceptor interceptor : storageInterceptors) { SafeRunner.run(new ISafeRunnable() { @Override public void run() { interceptor.destroy(); } @Override public void handleException(Throwable t) { BackupPlugin.getDefault().logError("error while destroying storage interceptor", t); //$NON-NLS-1$ } }); } } finally { monitor.done(); } } }; ProgressMonitorDialog dlg = new ProgressMonitorDialog(getShell()); try { dlg.run(true, false, runnable); } catch (InvocationTargetException e) { // TODO BackupPlugin.getDefault().logError("Error while closing backup database", e); //$NON-NLS-1$ } catch (InterruptedException e) { // not cancelable } System.gc(); return super.close(); }
From source file:edmondskarp.Controller.EdmondsKarpController.java
public void openState(String s) throws JSONException { if (s == null || s.equals("")) { graph.clearGraph();//from ww w . java 2s .c om gui.getCircles().clear(); name = 0; gui.update(); return; } Map<String, Circle> circles = new HashMap<>(); graph.clearGraph(); int maxIndex = 0; JSONObject jNodeEdge = new JSONObject(s); // Parse the JSON to a JSONObject JSONArray jNodes = jNodeEdge.getJSONArray("Node"); JSONArray jEdges = jNodeEdge.getJSONArray("Edge"); for (int i = 0; i < jNodes.length(); i++) { // Loop over each each row of node Circle circle = new Circle(); Point point = new Point(); JSONObject jNode = jNodes.getJSONObject(i); point.setLocation(jNode.getInt("PosX"), jNode.getInt("PosY")); circle.setFirstPoint(point); circle.addNode(graph.addNode("" + jNode.getString("ID"))); circles.put(jNode.getString("ID"), circle); if (jNode.getInt("ID") > maxIndex) { maxIndex = jNode.getInt("ID"); } } name = ++maxIndex; for (int i = 0; i < jEdges.length(); i++) { // Loop over each each row of edge JSONObject jEdge = jEdges.getJSONObject(i); Edge e = graph.connect(jEdge.getString("From"), jEdge.getString("To"), jEdge.getInt("Capacity"), 0); if (e == null) { graph.checkInverseArrowConnection(jEdge.getString("From"), jEdge.getString("To"), jEdge.getInt("Capacity")); } else { Arrow arrow = new Arrow(circles.get(jEdge.getString("From")), circles.get(jEdge.getString("To"))); arrow.setEdge(e); circles.get(jEdge.getString("From")).addArrowFrom(arrow); circles.get(jEdge.getString("To")).addArrowTo(arrow); } } if (!jNodeEdge.getString("Source").equals("")) { graph.setSource(graph.getNode(jNodeEdge.getString("Source"))); } if (!jNodeEdge.getString("Sink").equals("")) { graph.setSink(graph.getNode(jNodeEdge.getString("Sink"))); } gui.setCircles(new ArrayList(circles.values())); gui.update(); System.gc(); }
From source file:org.ofbiz.common.CommonServices.java
public static Map<String, Object> forceGc(DispatchContext dctx, Map<String, ?> context) { System.gc(); return ServiceUtil.returnSuccess(); }
From source file:br.com.carlosrafaelgn.fplay.ActivityBrowserRadio.java
private void addPlaySelectedItem(final boolean play) { if (radioStationList.getSelection() < 0) return;//from www. ja v a2s.c om try { final RadioStation radioStation = radioStationList.getItemT(radioStationList.getSelection()); if (radioStation.m3uUri == null || radioStation.m3uUri.length() < 0) { UI.toast(getApplication(), R.string.error_file_not_found); return; } Player.songs.addingStarted(); SongAddingMonitor.start(getHostActivity()); (new Thread("Checked Radio Station Adder Thread") { @Override public void run() { AndroidHttpClient client = null; HttpResponse response = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { if (Player.getState() == Player.STATE_TERMINATED || Player.getState() == Player.STATE_TERMINATING) { Player.songs.addingEnded(); return; } client = AndroidHttpClient.newInstance( "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36 Debian"); response = client.execute(new HttpGet(radioStation.m3uUri)); final StatusLine statusLine = response.getStatusLine(); final int s = statusLine.getStatusCode(); if (s == HttpStatus.SC_OK) { is = response.getEntity().getContent(); isr = new InputStreamReader(is, "UTF-8"); br = new BufferedReader(isr, 1024); ArrayList<String> lines = new ArrayList<String>(8); String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#' && (line.regionMatches(true, 0, "http://", 0, 7) || line.regionMatches(true, 0, "https://", 0, 8))) lines.add(line); } if (Player.getState() == Player.STATE_TERMINATED || Player.getState() == Player.STATE_TERMINATING) { Player.songs.addingEnded(); return; } if (lines.size() == 0) { Player.songs.addingEnded(); MainHandler.toast(R.string.error_gen); } else { //instead of just using the first available address, let's use //one from the middle ;) Player.songs.addFiles(new FileSt[] { new FileSt(lines.get(lines.size() >> 1), radioStation.title, null, 0) }, null, 1, play, false, true); } } else { Player.songs.addingEnded(); MainHandler.toast( (s >= 400 && s < 500) ? R.string.error_file_not_found : R.string.error_gen); } } catch (Throwable ex) { Player.songs.addingEnded(); MainHandler.toast(ex); } finally { try { if (client != null) client.close(); } catch (Throwable ex) { } try { if (is != null) is.close(); } catch (Throwable ex) { } try { if (isr != null) isr.close(); } catch (Throwable ex) { } try { if (br != null) br.close(); } catch (Throwable ex) { } br = null; isr = null; is = null; client = null; response = null; System.gc(); } } }).start(); } catch (Throwable ex) { Player.songs.addingEnded(); UI.toast(getApplication(), ex.getMessage()); } }
From source file:com.ettrema.zsync.IntegrationTests.java
/** * Creates the zsync File for servercopy, and saves it to a File with name fileName * @param fileName The name of the file in which to save the zsync data * @param blocksize The block size to use in MetaFileMaker * @return The created zsync File/* ww w . j a va 2s . c o m*/ * @throws FileNotFoundException */ private File createMetaFile(String fileName, int blocksize, File serverFile) throws FileNotFoundException { System.out.println("---------------- createMetaFile -------------------"); System.gc(); Runtime rt = Runtime.getRuntime(); startUsed = rt.totalMemory() - rt.freeMemory(); MetaFileMaker mkr = new MetaFileMaker(); File zsfile = mkr.make(null, blocksize, serverFile); System.gc(); System.out.println("Memory stats: " + formatBytes(rt.maxMemory()) + " - " + formatBytes(rt.totalMemory()) + " - " + formatBytes(rt.freeMemory())); long endUsed = (rt.totalMemory() - rt.freeMemory()); System.out.println("Start used memory: " + formatBytes(startUsed) + " end used memory: " + formatBytes(endUsed) + " - delta: " + formatBytes(endUsed - startUsed)); File dest = new File(filepath + fileName); if (dest.exists()) { if (!dest.delete()) { throw new RuntimeException("Failed to delete previous meta file: " + dest.getAbsolutePath()); } } System.out.println("rename meta file to: " + dest.getAbsolutePath()); if (!zsfile.renameTo(dest)) { throw new RuntimeException("Failed to rename to: " + dest.getAbsolutePath()); } System.out.println("Created meta file of size: " + formatBytes(dest.length()) + " from source file of size: " + formatBytes(serverFile.length())); System.out.println(""); return dest; }
From source file:com.chuannuo.tangguo.net.TGHttpResponseHandler.java
byte[] getResponseData(HttpEntity entity) throws IOException { byte[] responseBody = null; if (entity != null) { InputStream instream = entity.getContent(); if (instream != null) { long contentLength = entity.getContentLength(); if (contentLength > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); }// w w w.j a va2 s . co m int buffersize = (contentLength <= 0) ? BUFFER_SIZE : (int) contentLength; try { ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize); try { byte[] tmp = new byte[BUFFER_SIZE]; long count = 0; int l; // do not send messages if request has been cancelled while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) { count += l; buffer.append(tmp, 0, l); sendProgressMessage(count, (contentLength <= 0 ? 1 : contentLength)); } } finally { TGHttpClient.silentCloseInputStream(instream); TGHttpClient.endEntityViaReflection(entity); } responseBody = buffer.toByteArray(); } catch (OutOfMemoryError e) { System.gc(); throw new IOException("File too large to fit into available memory"); } } } return responseBody; }
From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java
/** * Adds all enlisted plans to an XML document, but does NOT write binary data. * Instead the Id's of all referenced uploads and sample records are added to the provided lists, * this way they can be added later.//from w w w. j a v a 2 s . co m * * @param ppids * @param uploadIDs * @param recordIDs * @return */ public Document exportToXml(List<Integer> ppids, List<Integer> uploadIDs, List<Integer> recordIDs) { ProjectExporter exporter = new ProjectExporter(); Document doc = exporter.createProjectDoc(); int i = 0; for (Integer id : ppids) { // load one plan after the other: List<Plan> list = em.createQuery("select p from Plan p where p.planProperties.id = " + id) .getResultList(); if (list.size() != 1) { FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "Skipping the export of the plan with properties" + id + ": Couldnt load."); } else { //log.debug("adding project "+p.getplanProperties().getName()+" to XML..."); exporter.addProject(list.get(0), doc, uploadIDs, recordIDs); } list.clear(); list = null; log.info("XMLExport: addString destinationed project ppid=" + id); i++; if ((i % 10 == 0)) { em.clear(); System.gc(); } } return doc; }
From source file:edu.uc.rphash.tests.kmeanspp.KMeansPlusPlus.java
public static void main(String[] args) { GenerateData gen = new GenerateData(3, 5000, 2, .1f); KMeansPlusPlus<DoublePoint> kk = new KMeansPlusPlus<>(gen.data(), 3); System.out.println(StatTests.WCSSECentroidsFloat(kk.getCentroids(), gen.getData())); System.gc(); }
From source file:com.panet.imeta.job.entries.deletefiles.JobEntryDeleteFiles.java
private boolean ProcessFile(String filename, String wildcard, Job parentJob) { LogWriter log = LogWriter.getInstance(); boolean rcode = false; FileObject filefolder = null; String realFilefoldername = environmentSubstitute(filename); String realwildcard = environmentSubstitute(wildcard); try {/* w w w . ja v a2 s. co m*/ filefolder = KettleVFS.getFileObject(realFilefoldername); // Here gc() is explicitly called if e.g. createfile is used in the // same // job for the same file. The problem is that after creating the // file the // file object is not properly garbaged collected and thus the file // cannot // be deleted anymore. This is a known problem in the JVM. System.gc(); if (filefolder.exists()) { // the file or folder exists if (filefolder.getType() == FileType.FOLDER) { // It's a folder if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryDeleteFiles.ProcessingFolder", realFilefoldername)); //$NON-NLS-1$ // Delete Files int Nr = filefolder .delete(new TextFileSelector(filefolder.toString(), realwildcard, parentJob)); if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryDeleteFiles.TotalDeleted", String.valueOf(Nr))); //$NON-NLS-1$ rcode = true; } else { // It's a file if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobEntryDeleteFiles.ProcessingFile", realFilefoldername)); //$NON-NLS-1$ boolean deleted = filefolder.delete(); if (!deleted) { log.logError(toString(), Messages.getString("JobEntryDeleteFiles.CouldNotDeleteFile", realFilefoldername)); //$NON-NLS-1$ } else { if (log.isBasic()) log.logBasic(toString(), Messages.getString("JobEntryDeleteFiles.FileDeleted", filename)); //$NON-NLS-1$ rcode = true; } } } else { // File already deleted, no reason to try to delete it if (log.isBasic()) log.logBasic(toString(), Messages.getString("JobEntryDeleteFiles.FileAlreadyDeleted", realFilefoldername)); //$NON-NLS-1$ rcode = true; } } catch (IOException e) { log.logError(toString(), Messages.getString("JobEntryDeleteFiles.CouldNotProcess", realFilefoldername, e.getMessage())); //$NON-NLS-1$ } finally { if (filefolder != null) { try { filefolder.close(); } catch (IOException ex) { } ; } } return rcode; }