List of usage examples for java.lang.ref SoftReference SoftReference
public SoftReference(T referent)
From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.AppObj.java
private String getRenderableClause() { if (mRenderableClause != null) { String renderable = mRenderableClause.get(); if (renderable != null) { return renderable; }/*from www . j a va2 s . c om*/ } StringBuffer allowed = new StringBuffer(); String[] types = DbObjects.getRenderableTypes(); for (String type : types) { if (!AppObj.TYPE.equals(type)) { allowed.append(",'").append(type).append("'"); } } String clause = DbObject.TYPE + " in (" + allowed.substring(1) + ")"; mRenderableClause = new SoftReference<String>(clause); return clause; }
From source file:com.gfan.sbbs.utils.images.ImageManager.java
/** * file/URLBitmap/*from w w w .j ava2s . c om*/ * * @param file * file URL/file PATH * @param bitmap * @param quality * @throws HttpException * @throws IOException * @throws ClientProtocolException */ public Bitmap safeGet(String file) throws HttpException { Bitmap bitmap = lookupFile(file); // first try file. if (bitmap != null) { synchronized (this) { // memory cache mCache.put(file, new SoftReference<Bitmap>(bitmap)); } return bitmap; } else { // get from web String url = file; bitmap = downloadImage2(url); // // put(file, bitmap); // file Cache return bitmap; } }
From source file:com.bah.bahdit.main.plugins.fulltextindex.FullTextIndex.java
/** * Search by using a full text index table. The entire text body of the * website is analyzed against the query and used to provide a ranking for * all the websites against the query. Only returns the number of results * requested, and only for a certain page. Assumes that all pages have the * same number of results. /*ww w. j a v a 2 s. co m*/ * (i.e. page 4, 10 results per page => results ranked 31-40) * * @param strQuery - string query to be looked up in the table * @param page - the page requested by the servlet * @param resultsPerPage - the number of results requested * * @return a SearchResults object, containing : * - ArrayList of URL info (rank, title, url) * - One possible correction for the query (if there are no results) * - The total number of results found (not necessarily returned) * - Total time needed to find the results */ @Override public SearchResults search(Object strQuery, int page, int resultsPerPage) { // used as base starting time to calculate time spent searching for results long startTime = System.nanoTime(); // we assume that the query is a string of terms String query = (String) strQuery; // checks if the query is in the memory cache // if so, get the results straight from the cache instead of accumulo String cacheString = query + String.valueOf(page); if (searchResultsCache.containsKey(cacheString)) { SearchResults s = searchResultsCache.get(cacheString).get(); if (s != null) { // save time needed to get from cache s.setTime(System.nanoTime() - startTime); return s; } // get rid of any keys that point to null else searchResultsCache.remove(cacheString); } // initialize the scanner that looks through the main table Scanner mainScanner = null; // set the main table to scan through String mainTable = properties.getProperty(FT_TABLE_NAME); // makes sure table has been created // if not, close program and exit if (!conn.tableOperations().exists(mainTable)) { log.error("FATAL: The tables do not exist. Please run ingest."); System.exit(1); } try { mainScanner = conn.createScanner(mainTable, new Authorizations()); } catch (TableNotFoundException e) { log.error(e.getMessage()); } // store the sampling table for tf-idf calculations String sampleTableString = null; try { sampleTableString = new String(Utils.serialize(sampleTable), ENCODING); } catch (UnsupportedEncodingException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } // store the pagerank table for pagerank calculations String pagerankTableString = null; try { pagerankTableString = new String(Utils.serialize(pagerankTable), ENCODING); } catch (UnsupportedEncodingException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } // put the necessary properties into the hashmap for the iterators Map<String, String> iteratorProperties = new HashMap<String, String>(); iteratorProperties.put(Search.QUERY, query); iteratorProperties.put(Search.PAGE, String.valueOf(page)); iteratorProperties.put(Search.NUM_RESULTS, String.valueOf(resultsPerPage)); iteratorProperties.put(Search.MAX_NGRAMS, properties.getProperty(Search.MAX_NGRAMS)); iteratorProperties.put(FT_SAMPLE, sampleTableString); iteratorProperties.put(Search.PAGERANK_TABLE, pagerankTableString); // this iterator calculates the rank of each document IteratorSetting cfg = new IteratorSetting(RANK_CALCULATOR_PRIORITY, RankCalculator.class, iteratorProperties); mainScanner.addScanIterator(cfg); // this iterator sorts the ranks of each document IteratorSetting cfg2 = new IteratorSetting(DOCUMENT_RANKER_PRIORITY, DocumentRanker.class, iteratorProperties); mainScanner.addScanIterator(cfg2); // Uses a sample table to determine which rowid to search for // Look for the least frequent term to best limit the number of documents String minTerm = ""; Integer min = null; for (String s : query.split(" ")) { // replace terms in query that are in the stop words list if (stopWords.contains(s)) { query = query.replaceAll(s, ""); continue; } // set the term with the minimum frequency from the sample table if (sampleTable.containsKey(s) && (min == null || sampleTable.get(s) < min)) { min = sampleTable.get(s); minTerm = s; } } // initialize internal objects for search results String correction = ""; ArrayList<String> urls = null; FixedSizePQ<Term> urlsPQ = null; int numResults = 0; // if all terms appear in sample table, look up in accumulo table if (!minTerm.equals("")) { // holds the information for each URL to be returned urls = new ArrayList<String>(); urlsPQ = new FixedSizePQ<Term>(page * resultsPerPage, new TermComparator()); // limit the search based on the minimum term // rows are created as : "[minTerm] [timestamp]" mainScanner.setRange(new Range(minTerm + " ", minTerm + "!")); // used to store the last column qualifier of each string String lastCQ = ""; // scan through the rows of the table using the pre-added iterators for (Entry<Key, Value> entry : mainScanner) { Double rank = 0.0; Key key = entry.getKey(); // get the cosim of the current entry try { rank = (Double) Utils.deserialize(entry.getValue().get()); } catch (IOException e) { log.error(e.getMessage()); } catch (ClassNotFoundException e) { log.error(e.getMessage()); } // add the current entry to the priority queue urlsPQ.add(new Term(key, rank)); // checks the last column qualifier for the number of total results lastCQ = key.getColumnQualifier().toString(); if (lastCQ.contains(NUM_RESULTS)) { lastCQ = lastCQ.replaceAll(KEEP_NUMBERS, ""); numResults += Integer.parseInt(lastCQ); } } } int i = resultsPerPage; // limit results if at the last of rankings if (resultsPerPage * page > numResults) i = numResults - (resultsPerPage * (page - 1)); // get only the specific urls we want from the back of the priority queue if (urlsPQ != null) { while (!urlsPQ.isEmpty() && i > 0) { Term t = urlsPQ.pollFirst(); urls.add(t.getValue() + "[ ]" + t.getKey().getColumnFamily().toString()); i--; } } // reverse the arraylist to get the correct highest to lowest order if (urls != null) Collections.reverse(urls); // if no results, assume misspelling and look for alternatives if (numResults == 0) correction = fullTextLevDistance(query, sampleTable, spellChecker); // get the total amount of time needed to get all the results long timeElapsed = System.nanoTime() - startTime; SearchResults results = new SearchResults(urls, correction, numResults, timeElapsed); // if there are results, store in cache for future searches if (numResults != 0) searchResultsCache.put(cacheString, new SoftReference<SearchResults>(results)); return results; }
From source file:com.gfan.sbbs.utils.images.ImageManager.java
/** * /*from w ww .j a v a 2s.c o m*/ * * @param file * file URL/file PATH * @param bitmap * @param quality */ @Override public Bitmap get(String file) { SoftReference<Bitmap> ref; Bitmap bitmap; // Look in memory first. synchronized (this) { ref = mCache.get(file); } if (ref != null) { bitmap = ref.get(); if (bitmap != null) { return bitmap; } } // Now try file. bitmap = lookupFile(file); if (bitmap != null) { synchronized (this) { mCache.put(file, new SoftReference<Bitmap>(bitmap)); } return bitmap; } // TODO: why? // upload: see profileImageCacheManager line 96 Log.w(TAG, "Image is missing: " + file); // return the default photo return mDefaultBitmap; }
From source file:org.apache.ctakes.ytex.kernel.IntrinsicInfoContentEvaluatorImpl.java
@Override public void evaluateIntrinsicInfoContent(String conceptGraphName, String conceptGraphDir, ConceptGraph cg) throws IOException { log.info("computing subsumer counts"); // compute the subsumer count Map<String, IntrinsicICInfo> icInfoMap = new HashMap<String, IntrinsicICInfo>(); Map<String, Set<String>> subsumerMap = new WeakHashMap<String, Set<String>>(); short[] depthArray = new short[cg.getConceptList().size()]; BufferedWriter w = null;//from w w w .j a v a2 s.c o m try { w = this.getOutputFile(conceptGraphName, conceptGraphDir, "subsumer"); computeSubsumerCount(cg.getConceptMap().get(cg.getRoot()), icInfoMap, subsumerMap, depthArray, w); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } } subsumerMap = null; log.info("computing max leaves"); // get the leaves in this concept graph Set<String> leafSet = null; try { w = this.getOutputFile(conceptGraphName, conceptGraphDir, "allleaf"); leafSet = this.getAllLeaves(cg, w); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } } log.info("computing leaf counts"); @SuppressWarnings("unchecked") SoftReference<HashSet<Integer>>[] leafCache = (SoftReference<HashSet<Integer>>[]) Array.newInstance( (new SoftReference<HashSet<Integer>>(new HashSet<Integer>())).getClass(), cg.getConceptList().size()); // compute leaf count of all concepts in this graph try { w = this.getOutputFile(conceptGraphName, conceptGraphDir, "leaf"); // for (String leaf : leafSet) { // computeLeafCount(cg.getConceptMap().get(leaf), icInfoMap, // leafCache, cg, w); // } this.getLeaves(cg.getConceptMap().get(cg.getRoot()), leafCache, icInfoMap, cg, w, null); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } } leafCache = null; log.info("storing intrinsic ic"); storeIntrinsicIC(conceptGraphName, leafSet.size(), icInfoMap, depthArray, cg); log.info("finished computing intrinsic ic"); }
From source file:com.gelakinetic.mtgfam.helpers.lruCache.ImageCache.java
/** * Initialize the cache, providing all parameters. * * @param cacheParams The cache parameters to initialize the cache *///from w w w . j a va2s .c om private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; //BEGIN_INCLUDE(init_memory_cache) // Set up memory cache if (mCacheParams.memoryCacheEnabled) { // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be // populated into the inBitmap field of BitmapFactory.Options. Note that the set is // of SoftReferences which will actually not be very effective due to the garbage // collector being aggressive clearing Soft/WeakReferences. A better approach // would be to use a strongly references bitmaps, however this would require some // balancing of memory usage between this set and the bitmap LruCache. It would also // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean // the size would need to be precise, from KitKat onward the size would just need to // be the upper bound (due to changes in how inBitmap can re-use bitmaps). // if (Utils.hasHoneycomb()) { // mReusableBitmaps = // Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>()); // } mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) { /** * Notify the removed entry that is no longer being cached */ @Override protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) { if (RecyclingBitmapDrawable.class.isInstance(oldValue)) { // The removed entry is a recycling drawable, so notify it // that it has been removed from the memory cache ((RecyclingBitmapDrawable) oldValue).setIsCached(false); } else { // The removed entry is a standard BitmapDrawable if (Utils.hasHoneycomb()) { // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap())); } } } /** * Measure item size in kilobytes rather than units which is more practical * for a bitmap cache */ @Override protected int sizeOf(String key, BitmapDrawable value) { final int bitmapSize = getBitmapSize(value) / 1024; return bitmapSize == 0 ? 1 : bitmapSize; } }; } //END_INCLUDE(init_memory_cache) // By default the disk cache is not initialized here as it should be initialized // on a separate thread due to disk access. if (cacheParams.initDiskCacheOnCreate) { // Set up disk cache initDiskCache(); } }
From source file:com.DGSD.Teexter.Utils.ContactPhotoManager.java
/** * If necessary, decodes bytes stored in the holder to Bitmap. As long as * the bitmap is held either by {@link #mBitmapCache} or by a soft reference * in the holder, it will not be necessary to decode the bitmap. *//* w w w.j a v a 2 s . c o m*/ private static void inflateBitmap(BitmapHolder holder) { byte[] bytes = holder.bytes; if (bytes == null || bytes.length == 0) { return; } // Check the soft reference. If will be retained if the bitmap is also // in the LRU cache, so we don't need to check the LRU cache explicitly. if (holder.bitmapRef != null) { holder.bitmap = holder.bitmapRef.get(); if (holder.bitmap != null) { return; } } try { Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null); holder.bitmap = bitmap; holder.bitmapRef = new SoftReference<Bitmap>(bitmap); } catch (OutOfMemoryError e) { // Do nothing - the photo will appear to be missing } }
From source file:com.eamonndunne.londontraffic.view.ImageCache.java
/** * Initialize the cache, providing all parameters. * * @param cacheParams The cache parameters to initialize the cache *///from www . j a va2 s . co m private void init(ImageCacheParams cacheParams) { mCacheParams = cacheParams; //BEGIN_INCLUDE(init_memory_cache) // Set up memory cache if (mCacheParams.memoryCacheEnabled) { // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be // populated into the inBitmap field of BitmapFactory.Options. Note that the set is // of SoftReferences which will actually not be very effective due to the garbage // collector being aggressive clearing Soft/WeakReferences. A better approach // would be to use a strongly references bitmaps, however this would require some // balancing of memory usage between this set and the bitmap LruCache. It would also // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean // the size would need to be precise, from KitKat onward the size would just need to // be the upper bound (due to changes in how inBitmap can re-use bitmaps). if (Utils.hasHoneycomb()) { mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>()); } mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) { /** * Notify the removed entry that is no longer being cached */ @Override protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) { if (RecyclingBitmapDrawable.class.isInstance(oldValue)) { // The removed entry is a recycling drawable, so notify it // that it has been removed from the memory cache ((RecyclingBitmapDrawable) oldValue).setIsCached(false); } else { // The removed entry is a standard BitmapDrawable if (Utils.hasHoneycomb()) { // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap())); } } } /** * Measure item size in kilobytes rather than units which is more practical * for a bitmap cache */ @Override protected int sizeOf(String key, BitmapDrawable value) { final int bitmapSize = getBitmapSize(value) / 1024; return bitmapSize == 0 ? 1 : bitmapSize; } }; } //END_INCLUDE(init_memory_cache) // By default the disk cache is not initialized here as it should be initialized // on a separate thread due to disk access. if (cacheParams.initDiskCacheOnCreate) { // Set up disk cache initDiskCache(); } }
From source file:edu.stanford.muse.webapp.Sessions.java
/** * return the public archive specified by archiveId. the archive is shared by all clients. * if the archive has never been loaded or has been garbage collected (due to weak ref), * will load the "default" file from <default_root_dir>/<archive_file>/ where archive_file * is determined by archiveId according to <default_root_dir>/archives.xml. * TODO: following session attributes will also be set in the given session (for compatibility * with the code being shared with Desktop mode in newBrowse.jsp, etc.): * "archive", "emailDocs", "lexicon"./*from w w w. j a v a2 s . co m*/ * @param session * @param archiveId * @return * @throws CorruptIndexException * @throws LockObtainFailedException * @throws IOException */ public static Archive loadSharedArchiveAndPrepareSession(HttpSession session, String archiveId) throws IOException { Util.ASSERT(ModeConfig.isMultiUser()); log.info("Loading shared session: " + archiveId); Archive result = null; if (Util.nullOrEmpty(archiveId)) return result; String userKey = getArchiveInfoMap(archiveId).get("file"); // this is equivalent to userKey if (Util.nullOrEmpty(userKey)) return result; // reload the archive on-demand if necessary String title = "default"; String baseDir = getDefaultRootDir() + File.separatorChar + userKey; String filename = getSessionFilename(baseDir, title); if (!new File(filename).exists()) return result; synchronized (globalSessions) { if (!globalSessions.containsKey(filename)) { // has never been loaded = need a fresh load. log.info("Archive has not been loaded, needs a fresh load: " + archiveId); globalSessions.put(filename, new SoftReference<Map<String, Object>>(null)); removeAllAttributes(session); } else log.info("Good, archive has already been loaded: " + archiveId); } Map<String, Object> loaded_map = null; try { log.info("Loading global session from basedir: " + baseDir + " filename: " + filename); loaded_map = getGlobalSession(filename, baseDir); // perform the actual load } catch (Exception e) { Util.print_exception(e, log); } if (!Util.nullOrEmpty(loaded_map)) { result = (Archive) loaded_map.get("archive"); if (result != null && session != null) { session.setAttribute("archive", result); session.setAttribute("emailDocs", result.getAllDocs()); session.setAttribute("lexicon", result.getLexicon("general")); } } return result; }
From source file:com.silverwrist.dynamo.unistore.TextPartImpl.java
public synchronized String getText() throws DatabaseException { if (m_ops == null) throw new DatabaseException(TextPartImpl.class, "UniStoreMessages", "part.deleted"); String rc = null;/* w ww. j a v a 2s .c o m*/ if (m_text != null) rc = (String) (m_text.get()); if (rc == null) { // load text fom database and reload to reference rc = m_ops.getText(m_parent.getMessageID(), m_part); m_text = new SoftReference(rc); } // end if return rc; }