List of usage examples for java.lang System gc
public static void gc()
From source file:com.quix.aia.cn.imo.rest.AddressBookRest.java
/** * <p>/*w w w . j av a 2 s .c o m*/ * This method retrieves List of Address Book for particular Agent. * </p> * * @param agentId * */ @GET @Path("/getAgentAddressBook") @Produces(MediaType.APPLICATION_JSON) public Response getAgentAddressBook(@Context HttpServletRequest request, @Context ServletContext context) { log.log(Level.INFO, "Address Book --> getAgentAddressBook "); GsonBuilder builder = new GsonBuilder(); AddressBookMaintenance addressBookMaintenance = new AddressBookMaintenance(); Gson googleJson = null; MsgBeans beans = new MsgBeans(); AuditTrailMaintenance auditTrailMaint = new AuditTrailMaintenance(); List<AddressBook> addressBookList = new ArrayList(); String jsonString = ""; try { builder.registerTypeHierarchyAdapter(byte[].class, new JsonSerializer<byte[]>() { public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(Base64.encodeBase64String(src)); } }); googleJson = builder.setDateFormat("yyyy-MM-dd HH:mm:ss").create(); log.log(Level.INFO, "Address Book --> fetching Information ... "); addressBookList = addressBookMaintenance.getAgentAddressBook(request, context); // Convert the object to a JSON string log.log(Level.INFO, "Address Book --> Information fetched successfully... "); jsonString = googleJson.toJson(addressBookList); return Response.status(200).entity(jsonString).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 fetching 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 { addressBookList.clear(); auditTrailMaint = null; addressBookMaintenance = null; jsonString = null; beans = null; builder = null; googleJson = null; System.gc(); } }
From source file:io.cloudslang.worker.management.services.InBuffer.java
public boolean checkFreeMemorySpace(long threshold) { double allocatedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); double presumableFreeMemory = Runtime.getRuntime().maxMemory() - allocatedMemory; boolean result = presumableFreeMemory > threshold; if (!result) { logger.warn("InBuffer would not poll messages, because there is not enough free memory."); if (System.currentTimeMillis() > (gcTimer + MINIMUM_GC_DELTA)) { logger.warn("Trying to initiate garbage collection"); //Todo find a better solution than manually triggering GC System.gc(); gcTimer = System.currentTimeMillis(); }/*from w ww . j a va 2 s.c o m*/ } return result; }
From source file:at.stefanproell.ResultSetVerification.ResultSetVerificationAPI.java
/** * Calculate hash on DB//from w w w . java 2 s. co m * * @return */ public String retrieveFullResultSet(ResultSet rs) { this.logger.info("Resulset row count: " + this.getResultSetRowCount(rs)); String resultSetHash = ""; String currentHash = ""; String previousKey = ""; String compositeHash = ""; int hashCounter = 0; long startTime = System.currentTimeMillis(); //int hashCounter =0; try { ResultSetMetaData rsmd = rs.getMetaData(); int columnsNumber = rsmd.getColumnCount(); this.logger.info("There are " + columnsNumber + " columns in the result set"); String newResultSetHash = null; long meanTimeStart = System.currentTimeMillis(); rs.setFetchSize(1000); while (rs.next()) { hashCounter++; if (hashCounter % 1000 == 0) { long meanTimeStop = System.currentTimeMillis(); this.logger.warning("Calculated " + hashCounter + " hashes so far. This batch took " + (double) ((meanTimeStop - meanTimeStart) / 1000) + " seconds"); meanTimeStart = System.currentTimeMillis(); } for (int i = 1; i < columnsNumber; i++) { currentHash += rs.getString(i); } if (rs.isFirst()) { resultSetHash = this.calculateHashFromString(currentHash); } else { compositeHash = (resultSetHash + currentHash); // reset the variables in order to reduce overhead resultSetHash = null; currentHash = null; newResultSetHash = this.calculateHashFromString(compositeHash); //this.logger.info("[resultSetHash] "+resultSetHash + "[currentHash] " + currentHash +" -> // [newResultSetHash]" + newResultSetHash ); resultSetHash = newResultSetHash; } System.gc(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; double elapsedTime = (double) (totalTime / 1000); this.logger.info("Calculated " + hashCounter + " hash values in " + elapsedTime + " sec"); this.logger.info("Hash is " + resultSetHash); return resultSetHash; }
From source file:eu.scape_project.planning.xml.ProjectExportAction.java
/** * Writes the digital objects of the provided objectIds to the tempDir as * files./*w w w . j ava 2 s . c o m*/ * * @param objectIds * the IDs of the objects to write * @param tempDir * a temporary directory where the files will be written * @throws IOException * if an error occurred during write * @throws StorageException * if the objects could not be loaded */ private void writeDigitalObjects(List<Integer> objectIds, String tempDir) throws IOException, StorageException { int counter = 0; int skip = 0; log.info("Writing bytestreams of digital objects. Size = " + objectIds.size()); for (Integer id : objectIds) { if (counter > LOADED_DATA_SIZE_BOUNDARY) { // Call GC if unused data // exceeds boundary System.gc(); counter = 0; } DigitalObject object = em.find(DigitalObject.class, id); if (object.isDataExistent()) { counter += object.getData().getSize(); File f = new File(tempDir + object.getId() + ".xml"); DigitalObject dataFilledObject = digitalObjectManager.getCopyOfDataFilledDigitalObject(object); FileOutputStream out = new FileOutputStream(f); try { out.write(dataFilledObject.getData().getData()); } finally { out.close(); } dataFilledObject = null; } else { skip++; } object = null; } em.clear(); System.gc(); log.info("Finished writing bytestreams of digital objects. Skipped empty objects: " + skip); }
From source file:org.mariotaku.twidere.util.net.HttpClientImpl.java
@Override public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException { try {// w ww .j av a2 s .c om HttpRequestBase commonsRequest; final HostAddressResolver resolver = conf.getHostAddressResolver(); final String urlString = req.getURL(); final URI urlOrig; try { urlOrig = new URI(urlString); } catch (final URISyntaxException e) { throw new TwitterException(e); } final String host = urlOrig.getHost(), authority = urlOrig.getAuthority(); final String resolvedHost = resolver != null ? resolver.resolve(host) : null; final String resolvedUrl = !isEmpty(resolvedHost) ? urlString.replace("://" + host, "://" + resolvedHost) : urlString; final RequestMethod method = req.getMethod(); if (method == RequestMethod.GET) { commonsRequest = new HttpGet(resolvedUrl); } else if (method == RequestMethod.POST) { final HttpPost post = new HttpPost(resolvedUrl); // parameter has a file? boolean hasFile = false; final HttpParameter[] params = req.getParameters(); if (params != null) { for (final HttpParameter param : params) { if (param.isFile()) { hasFile = true; break; } } if (!hasFile) { if (params.length > 0) { post.setEntity(new UrlEncodedFormEntity(params)); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter param : params) { if (param.isFile()) { final ContentBody body; if (param.getFile() != null) { body = new FileBody(param.getFile(), param.getContentType()); } else { body = new InputStreamBody(param.getFileBody(), param.getFileName(), param.getContentType()); } me.addPart(param.getName(), body); } else { final ContentBody body = new StringBody(param.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(param.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (method == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolvedUrl); } else if (method == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolvedUrl); } else if (method == RequestMethod.PUT) { commonsRequest = new HttpPut(resolvedUrl); } else throw new TwitterException("Unsupported request method " + method); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } final Authorization authorization = req.getAuthorization(); final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req) : null; if (authorizationHeader != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) { commonsRequest.addHeader("Host", authority); } final ApacheHttpClientHttpResponseImpl res; try { res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf); } catch (final IllegalStateException e) { throw new TwitterException("Please check your API settings.", e); } catch (final NullPointerException e) { // Bug http://code.google.com/p/android/issues/detail?id=5255 throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e); } catch (final OutOfMemoryError e) { // I don't know why OOM thown, but it should be catched. System.gc(); throw new TwitterException("Unknown error", e); } final int statusCode = res.getStatusCode(); if (statusCode < OK || statusCode > ACCEPTED) throw new TwitterException(res.asString(), req, res); return res; } catch (final IOException e) { throw new TwitterException(e); } }
From source file:com.duroty.task.POP3ServiceTask.java
/** * DOCUMENT ME!/*from ww w . ja v a2 s.co m*/ * * @param user DOCUMENT ME! * @param mime DOCUMENT ME! * * @return DOCUMENT ME! */ private boolean isSpam(Users user, MimeMessage mime) { boolean control = false; double probability = 0.0; try { BayesianAnalysis bayesianAnalysis = new BayesianAnalysis(); bayesianAnalysis.init(null); bayesianAnalysis.service(user.getUseUsername(), null, mime); String[] aux = mime.getHeader(BayesianAnalysis.messageIsSpamProbability); if ((aux != null) && (aux.length > 0)) { for (int i = 0; i < aux.length; i++) { probability = Double.parseDouble(aux[i].trim()); break; } } Iterator it = user.getMailPreferenceses().iterator(); MailPreferences mailPreferences = (MailPreferences) it.next(); if (mailPreferences.getMaprSpamTolerance() == -1) { return false; } double tolerance = ((double) mailPreferences.getMaprSpamTolerance()) / 100; if ((probability > 0.0) && (tolerance < 1.0) && (probability >= tolerance)) { control = true; } return control; } catch (NamingException e) { return false; } catch (Exception ex) { return false; } catch (java.lang.OutOfMemoryError ex) { System.gc(); return false; } catch (Throwable ex) { return false; } }
From source file:com.cloudstudio.camera.ForegroundCameraLauncher.java
/** * Called when the camera view exits.//from www . j a v a 2 s. com * * @param requestCode * The request code originally supplied to * startActivityForResult(), allowing you to identify who this * result came from. * @param resultCode * The integer result code returned by the child activity through * its setResult(). * @param intent * An Intent, which can return result data to the caller (various * data can be attached to Intent "extras"). */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // If image available if (resultCode == Activity.RESULT_OK) { try { // Create an ExifHelper to save the exif data that is lost // during compression ExifHelper exif = new ExifHelper(); exif.createInFile( getTempDirectoryPath(this.cordova.getActivity().getApplicationContext()) + "/Pic.jpg"); exif.readExifData(); // Read in bitmap of captured image Bitmap bitmap; try { bitmap = android.provider.MediaStore.Images.Media .getBitmap(this.cordova.getActivity().getContentResolver(), imageUri); } catch (FileNotFoundException e) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver(); bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); } bitmap = scaleBitmap(bitmap); // Create entry in media store for image // (Don't use insertImage() because it uses default compression // setting of 50 - no way to change it) ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = null; try { Log.d("camera", "external_content_uri:" + android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); uri = this.cordova.getActivity().getContentResolver() .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { LOG.d(LOG_TAG, "Can't write to external media storage."); try { uri = this.cordova.getActivity().getContentResolver() .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { LOG.d(LOG_TAG, "Can't write to internal media storage."); this.failPicture("Error capturing image - no media storage found."); return; } } Log.d("camera", "uri:" + uri.toString()); // Add compressed version of captured image to returned media // store Uri OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); // Restore exif data to file exif.createOutFile(getRealPathFromURI(uri, this.cordova)); exif.writeExifData(); // Send Uri back to JavaScript for viewing image this.callbackContext.success(getRealPathFromURI(uri, this.cordova)); bitmap.recycle(); bitmap = null; System.gc(); checkForDuplicateImage(); } catch (IOException e) { e.printStackTrace(); this.failPicture("Error capturing image."); } } // If cancelled else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Camera cancelled."); } // If something else else { this.failPicture("Did not complete!"); } }
From source file:eu.planets_project.pp.plato.action.workflow.AbstractWorkflowStep.java
/** * //ww w . j a v a2 s . co m */ protected void doClearEm() { int projectId = selectedPlan.getId(); selectedPlan = null; em.clear(); selectedPlan = em.find(Plan.class, projectId); System.gc(); }
From source file:de.u808.simpleinquest.indexer.impl.IndexUpdater.java
private void indexDocuments(List<File> files) throws CorruptIndexException, LockObtainFailedException, IOException { IndexWriter indexWriter = new IndexWriter(indexDirectory, new StandardAnalyzer()); Iterator<File> iterator = files.iterator(); while (iterator.hasNext()) { File file = (File) iterator.next(); if (file.isDirectory()) { Document doc = DirectoryDocument.Document(file); indexWriter.addDocument(doc); } else {/*from w w w. ja v a 2 s . c om*/ Indexer indexer = indexerFactory.getIndexer(file); if (indexer != null) { Document document = null; try { log.debug("Memory before indexing in MB (M: " + memoryFormater.format(Runtime.getRuntime().maxMemory() / (1024 * 1024)) + " T: " + memoryFormater.format(Runtime.getRuntime().totalMemory() / (1024 * 1024)) + "F: " + memoryFormater.format(Runtime.getRuntime().freeMemory() / (1024 * 1024)) + ")"); this.ensureEnoughHeapMemory(); String msg = "Indexing file: " + file.getPath(); document = indexer.indexFile(file); this.setStatusMessage(msg); log.info(msg); log.debug("Memory after indexing in MB (M: " + memoryFormater.format(Runtime.getRuntime().maxMemory() / (1024 * 1024)) + " T: " + memoryFormater.format(Runtime.getRuntime().totalMemory() / (1024 * 1024)) + " F: " + memoryFormater.format(Runtime.getRuntime().freeMemory() / (1024 * 1024)) + ")"); iterator.remove(); } catch (IndexerException e) { log.error("Error during indexing", e); } catch (OutOfMemoryError outOfMemoryError) { log.warn( "File seems to be to big for the actual free heap. Try to increase availible memory with vm option -Xmx if this is a recurring error message"); log.info("Try to free memory"); document = null; System.gc(); this.refreschIndex(); } if (document != null) { indexWriter.addDocument(document); } else { String msg = "Indexer " + indexer.getClass() + " returned no content to index"; this.setStatusMessage(msg); log.warn(msg); } } else { log.debug("No indexer for file: " + file.getPath()); } } } String msg = "Optimizing index"; this.setStatusMessage(msg); log.info(msg); indexWriter.flush(); indexWriter.optimize(); msg = "Index optimized"; this.setStatusMessage(msg); log.info(msg); indexWriter.close(true); indexWriter = null; }