/** * Finds a JDT CUD for a given top-level type, generating it if needed. * * @param topType top-level JClassType * @return CUD instance or null if no source found */ private synchronized CompilationUnitDeclaration getCudForTopLevelType(JClassType topType) { CompilationUnitDeclaration cud = null; if (cudCache.containsKey(topType)) { SoftReference<CompilationUnitDeclaration> cudRef = cudCache.get(topType); if (cudRef != null) { cud = cudRef.get(); } } if (cud == null) { Resource classSource = classSources.get(topType); String source = null; if (classSource != null) { try { InputStream stream = classSource.openContents(); source = Util.readStreamAsString(stream); } catch (IOException ex) { throw new InternalCompilerException( "Problem reading resource: " + classSource.getLocation(), ex); } } if (source == null) { // cache negative result so we don't try again cudCache.put(topType, null); } else { cud = parseJava(source); cudCache.put(topType, new SoftReference<CompilationUnitDeclaration>(cud)); } } return cud; }
public Drawable loadDrawable( final String imageUrl, final ImageView imageView, final ImageCallback imageCallback) { if (imageCache.containsKey(imageUrl)) { SoftReference<Drawable> softReference = imageCache.get(imageUrl); Drawable drawable = softReference.get(); if (drawable != null) { return drawable; } } final Handler handler = new Handler() { public void handleMessage(Message message) { imageCallback.imageLoaded((Drawable) message.obj, imageView, imageUrl); } }; new Thread() { @Override public void run() { Drawable drawable = null; try { drawable = ImageUtil.geRoundDrawableFromUrl(imageUrl, 10); } catch (Exception e) { e.printStackTrace(); } imageCache.put(imageUrl, new SoftReference<Drawable>(drawable)); Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); } }.start(); return null; }
/** * 异步设置单张imageview图片,采取软引用 * * @param url 网络图片地址 * @param imageView 需要设置的imageview */ public static void setImageViewFromUrl(final String url, final ImageView imageView) { singImageView = imageView; // 如果软引用为空,就新建一个 if (singleImageCache == null) { singleImageCache = new HashMap<String, SoftReference<Drawable>>(); } // 如果软引用中已经有了相同的地址,就从软引用中获取 if (singleImageCache.containsKey(url)) { SoftReference<Drawable> soft = singleImageCache.get(url); Drawable draw = soft.get(); singImageView.setImageDrawable(draw); return; } final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { singImageView.setImageDrawable((Drawable) msg.obj); } }; // 子线程不能更新UI,又不然会报错 new Thread() { public void run() { Drawable drawable = loadImageFromUrl(url); if (drawable == null) { Log.e("single imageview", "single imageview of drawable is null"); } else { // 把已经读取到的图片放入软引用 singleImageCache.put(url, new SoftReference<Drawable>(drawable)); } Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); }; }.start(); }
/** Returns nickname cluster IDs or null. Maintains cache. */ protected String[] getCommonNicknameClusters(String normalizedName) { if (mNicknameBloomFilter == null) { preloadNicknameBloomFilter(); } int hashCode = normalizedName.hashCode(); if (!mNicknameBloomFilter.get(hashCode & NICKNAME_BLOOM_FILTER_SIZE)) { return null; } SoftReference<String[]> ref; String[] clusters = null; synchronized (mNicknameClusterCache) { if (mNicknameClusterCache.containsKey(normalizedName)) { ref = mNicknameClusterCache.get(normalizedName); if (ref == null) { return null; } clusters = ref.get(); } } if (clusters == null) { clusters = loadNicknameClusters(normalizedName); ref = clusters == null ? null : new SoftReference<String[]>(clusters); synchronized (mNicknameClusterCache) { mNicknameClusterCache.put(normalizedName, ref); } } return clusters; }
public static boolean clearWorldReference(World world) { String worldname = world.getName(); if (regionfiles == null) return false; if (rafField == null) return false; ArrayList<Object> removedKeys = new ArrayList<Object>(); try { for (Object o : regionfiles.entrySet()) { Map.Entry e = (Map.Entry) o; File f = (File) e.getKey(); if (f.toString().startsWith("." + File.separator + worldname)) { SoftReference ref = (SoftReference) e.getValue(); try { RegionFile file = (RegionFile) ref.get(); if (file != null) { RandomAccessFile raf = (RandomAccessFile) rafField.get(file); raf.close(); removedKeys.add(f); } } catch (Exception ex) { ex.printStackTrace(); } } } } catch (Exception ex) { MyWorlds.log( Level.WARNING, "Exception while removing world reference for '" + worldname + "'!"); ex.printStackTrace(); } for (Object key : removedKeys) { regionfiles.remove(key); } return true; }
/** Compile a schema. */ public Schema compileSchema(Path path) throws SAXException, IOException { String nativePath = path.getNativePath(); SoftReference<Schema> schemaRef = _schemaMap.get(path); Schema schema = null; if (schemaRef != null && (schema = schemaRef.get()) != null) { // XXX: probably eventually add an isModified return schema; } ReadStream is = path.openRead(); try { InputSource source = new InputSource(is); source.setSystemId(path.getUserPath()); schema = compileSchema(source); if (schema != null) _schemaMap.put(path, new SoftReference<Schema>(schema)); } finally { is.close(); } return schema; }
/** * @param url The URL of the image that will be retrieved from the cache. * @return The cached bitmap or null if it was not found. */ private Bitmap getBitmapFromCache(String url) { // First try the hard reference cache synchronized (sHardBitmapCache) { final Bitmap bitmap = sHardBitmapCache.get(url); if (bitmap != null) { // Bitmap found in hard cache // Move element to first position, so that it is removed last sHardBitmapCache.remove(url); sHardBitmapCache.put(url, bitmap); return bitmap; } } // Then try the soft reference cache SoftReference<Bitmap> bitmapReference = sSoftBitmapCache.get(url); if (bitmapReference != null) { final Bitmap bitmap = bitmapReference.get(); if (bitmap != null) { // Bitmap found in soft cache return bitmap; } else { // Soft reference has been Garbage Collected sSoftBitmapCache.remove(url); } } return null; }
@Test public void shouldAllowBackgroundThreadsToFinishUsingContextAfterOnDestroy() throws Exception { final SoftReference<F> ref = new SoftReference<F>(Robolectric.buildActivity(F.class).create().get()); final BlockingQueue<Context> queue = new ArrayBlockingQueue<Context>(1); new Thread() { final Context context = RoboGuice.getInjector(ref.get()).getInstance(Context.class); @Override public void run() { queue.add(context); } }.start(); ref.get().onDestroy(); // Force an OoM // http://stackoverflow.com/questions/3785713/how-to-make-the-java-system-release-soft-references/3810234 boolean oomHappened = false; try { @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) final ArrayList<Object[]> allocations = new ArrayList<Object[]>(); int size; while ((size = Math.min(Math.abs((int) Runtime.getRuntime().freeMemory()), Integer.MAX_VALUE)) > 0) allocations.add(new Object[size]); } catch (OutOfMemoryError e) { // Yeah! oomHappened = true; } assertTrue(oomHappened); assertNotNull(queue.poll(10, TimeUnit.SECONDS)); }
public V get(K key) { SoftReference<V> val = mTable.get(key); if (val == null) return null; V ret = val.get(); if (ret == null) mTable.remove(key); return ret; }
/** * 从缓存中获取图片 * * @param position * @return */ public Drawable getDrawableCache(final String url) { SoftReference<Drawable> softReference = mImageCache.get(url); if (softReference != null && softReference.get() != null && mCallBack != null) { return softReference.get(); } return null; }
public Bitmap getBitmap(String url) { Bitmap bit = mCache.get(url); if (bit == null) { /** 一级缓存没有拿到,从二级缓存中取 */ if (isDebug) System.out.println(id + "multicache -- 一级缓存没有获取到,准备从二级缓存中获取"); SoftReference<Bitmap> soft = softCache.get(url); if (soft == null) { /** 二级缓存没有拿到,文件中取得 */ if (isDebug) System.out.println(id + "multicache -- 二级缓存没有获取到,准备从文件中获取"); bit = BitmapUtils.readFromFile(fileCache, url); } else { /** 从二级缓存中获得 */ if (isDebug) System.out.println(id + "multicache -- 二级缓存获取到,但不确定是否存在bitmap"); bit = soft.get(); if (bit == null) { /** 二级缓存中被回收,文件中获取 */ if (isDebug) System.out.println(id + "multicache -- 二级缓存获取到但是被回收了,从文件中获取"); bit = BitmapUtils.readFromFile(fileCache, url); } else { /** 确实在二级缓存中,加入一级缓存,从二级缓存中移除 */ if (isDebug) System.out.println(id + "multicache -- 二级缓存获取到加入一级缓存,移除二级缓存"); mCache.put(url, bit); softCache.remove(soft); } } } else { if (isDebug) System.out.println(id + "multicache -- 从一级缓存中获取到"); } if (isDebug) { if (bit == null) System.out.println(id + "multicache -- 最终没有获取到,网络获取"); else System.out.println(id + "multicache -- 最终获取到资源------"); } return bit; }
/** * Returns the Bitmap associated with given key url. * * @param id url of bitmap. * @return Bitmap associated with the url. */ public Bitmap get(String id) { if (!cache.containsKey(id)) { return null; } SoftReference<Bitmap> ref = cache.get(id); return ref.get(); }
/** * 从缓存中获取key 指定的图片对象,并且指定缩放之后的尺寸 * * @param key * @param reqWidth * @param reqHeight * @return */ public Bitmap get(String key, int reqWidth, int reqHeight) { // Bitmap bm = mCache.get(key) == null ? null : mCache.get(key); // if (bm == null) { // if (reqWidth != 0 && reqHeight != 0) { // return this.getBitmapFromLocal(key, reqWidth, reqHeight); // }else { // bm = getBitmapFromLocal(key); // put(key, bm); // } // } Bitmap bm = null; // synchronized (mCache) { // bm = mCache.get(key); // if(bm == null) { if (mCache.containsKey(key)) { SoftReference<Bitmap> bitmapReference = mCache.get(key); bm = bitmapReference.get(); } else { if (reqWidth != 0 && reqHeight != 0) { return this.getBitmapFromLocal(key, reqWidth, reqHeight); } else { bm = getBitmapFromLocal(key); put(key, bm); } } // } // } return bm; }
/** 从缓存中获取图片 */ public Bitmap getBitmapFromCache(String url) { Bitmap bitmap; // 先从硬引用缓存中获取 synchronized (mLruCache) { bitmap = mLruCache.get(url); if (bitmap != null) { // 如果找到的话,把元素移到LinkedHashMap的最前面,从而保证在LRU算法中是最后被删除 mLruCache.remove(url); mLruCache.put(url, bitmap); System.out.println("硬引用中找到了"); return bitmap; } else { System.out.println("硬引用中没找到"); } } // 如果硬引用缓存中找不到,到软引用缓存中找 synchronized (mSoftCache) { SoftReference<Bitmap> bitmapReference = mSoftCache.get(url); if (bitmapReference != null) { bitmap = bitmapReference.get(); if (bitmap != null) { // 将图片移回硬缓存 mLruCache.put(url, bitmap); mSoftCache.remove(url); System.out.println("软引用中找到了"); return bitmap; } else { mSoftCache.remove(url); System.out.println("软引用中没找到"); } } } return null; }
// 传递的context可能销毁了 public Drawable loadDrawable(final List<String> imageUrls, final ImageCallback imageCallback) { if (imageUrls == null || imageUrls.size() == 0) { return null; } _imageUrl = imageUrls.get(0); if (_imageCache.containsKey(_imageUrl)) { SoftReference<Drawable> softReference = _imageCache.get(_imageUrl); Drawable drawable = softReference.get(); if (drawable != null) { Log.i("AsyncImageLoader", "AsyncLoader get drawable from cache"); return drawable; } } new Thread() { @Override public void run() { final Drawable drawable = loadImageFromUrl(_context, _imageUrl); _imageCache.put(_imageUrl, new SoftReference<Drawable>(drawable)); if (_context != null && drawable != null && imageCallback != null) { Activity activity = (Activity) _context; activity.runOnUiThread( new Runnable() { @Override public void run() { imageCallback.imageLoaded(drawable, _imageUrl); Log.i("AsyncImageLoader", "AsyncImageLoader get drawable from url"); } }); } } }.start(); return null; }
/** * Reports statistics detailing the image manager cache performance and the current size of the * cached images. */ protected void reportCachePerformance() { if ( /* Log.getLevel() != Log.log.DEBUG || */ _improv == null || _cacheStatThrottle.throttleOp()) { return; } // compute our estimated memory usage long amem = 0; int asize = 0; synchronized (_atiles) { // first total up the active tiles Iterator<SoftReference<Tile>> iter = _atiles.values().iterator(); while (iter.hasNext()) { SoftReference<Tile> sref = iter.next(); Tile tile = sref.get(); if (tile != null) { asize++; amem += tile.getEstimatedMemoryUsage(); } } } log.info( "Tile caches", "amem", (amem / 1024) + "k", "tmem", (Tile._totalTileMemory / 1024) + "k", "seen", _atiles.size(), "asize", +asize); }
private SoftKeyboard getKeyboard(KeyboardId id) { SoftReference<SoftKeyboard> ref = mKeyboards.get(id); SoftKeyboard keyboard = (ref == null) ? null : ref.get(); if (keyboard == null) { Resources orig = mInputMethodService.getResources(); Configuration conf = orig.getConfiguration(); Locale saveLocale = conf.locale; conf.locale = mInputLocale; orig.updateConfiguration(conf, null); if (mThemedContext != null) { keyboard = new SoftKeyboard(mThemedContext, id.mXml, id.mKeyboardMode, mThemeResId); } else { keyboard = new SoftKeyboard(mInputMethodService, id.mXml, id.mKeyboardMode); } keyboard.setLanguageSwitcher( mLanguageSwitcher, mIsAutoCompletionActive, mInputView.getLanguagebarTextColor(), mInputView.getLanguagebarShadowColor(), mLanguageSwitchMode); if (id.mEnableShiftLock) { keyboard.enableShiftLock(); } mKeyboards.put(id, new SoftReference<SoftKeyboard>(keyboard)); conf.locale = saveLocale; orig.updateConfiguration(conf, null); } return keyboard; }
public Drawable loadDrawable( final Context context, final String imageUrl, final ImageCallback imageCallback) { if (cacheMap.containsKey(imageUrl)) { SoftReference<Drawable> softReference = cacheMap.get(imageUrl); Drawable drawable = softReference.get(); if (drawable != null) { return drawable; } } final Handler handler = new Handler() { public void handleMessage(Message message) { imageCallback.imageLoaded((Drawable) message.obj, imageUrl); } }; executor.execute( new Runnable() { public void run() { Drawable drawable = loadImageFromUrl(context, imageUrl); if (null != drawable) cacheMap.put(imageUrl, new SoftReference<Drawable>(drawable)); Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); } }); return null; }
/** * Creates a {@link Tile} object from this tileset corresponding to the specified tile id and * returns that tile. A null tile will never be returned, but one with an error image may be * returned if a problem occurs loading the underlying tileset image. * * @param tileIndex the index of the tile in the tileset. Tile indexes start with zero as the * upper left tile and increase by one as the tiles move left to right and top to bottom over * the source image. * @param zations colorizations to be applied to the tile image prior to returning it. These may * be null for uncolorized images. * @return the tile object. */ public Tile getTile(int tileIndex, Colorization[] zations) { Tile tile = null; // first look in the active set; if it's in use by anyone or in the cache, it will be in // the active set synchronized (_atiles) { _key.tileSet = this; _key.tileIndex = tileIndex; _key.zations = zations; SoftReference<Tile> sref = _atiles.get(_key); if (sref != null) { tile = sref.get(); } } // if it's not in the active set, it's not in memory; so load it if (tile == null) { tile = createTile(); tile.key = new Tile.Key(this, tileIndex, zations); initTile(tile, tileIndex, zations); synchronized (_atiles) { _atiles.put(tile.key, new SoftReference<Tile>(tile)); } } // periodically report our image cache performance reportCachePerformance(); return tile; }
// 从缓存中获取Bitmap数据 public Bitmap getBitmapFromCache(String url) { Bitmap bitmap; // 加上同步锁保证同一时刻只执行一个对象 // 从硬引用获得数据 synchronized (mLruCache) { bitmap = mLruCache.get(url); if (bitmap != null) { // 如果有bitmap对象。则将这个对象从硬引用中先移除在添加。放到前面防止被逐出。 System.out.println("!!!!-----》命中硬存mLrucache"); mLruCache.remove(url); mLruCache.put(url, bitmap); return bitmap; } } // 从软引用获得数据 synchronized (mSoftCache) { SoftReference<Bitmap> bitmapReference = mSoftCache.get(url); if (bitmapReference != null) { bitmap = bitmapReference.get(); if (bitmap != null) { // 把存在的这个图片提升到硬缓存 System.out.println("!!!!命中软缓存mSoftCache"); } else { mSoftCache.remove(url); } } } return null; }
// 获取缩略图 public static Bitmap getScaledBitmap(String url) { // 前缀Scaled表明是缩略图 url = "Scaled" + url; Bitmap bitmap; String filename = convertUrlToFileName(url); String dir = getDirectory(filename); SoftReference<Bitmap> reference = map.get(filename); if (reference != null) { bitmap = reference.get(); if (bitmap != null) { updateFileTime(dir, filename); return bitmap; } } String pathName = dir + "/" + filename; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; updateFileTime(dir, filename); bitmap = BitmapFactory.decodeFile(pathName, options); reference = new SoftReference<>(bitmap); map.put(filename, reference); return bitmap; }
public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) { if (imageCache.containsKey(imageUrl)) { SoftReference<Drawable> softReference = imageCache.get(imageUrl); Drawable drawable = softReference.get(); if (drawable != null) { return drawable; } } final Handler handler = new Handler() { public void handleMessage(Message message) { imageCallback.imageLoaded((Drawable) message.obj, imageUrl); } }; new Thread() { @Override public void run() { Drawable drawable = loadImageFromUrl(imageUrl); imageCache.put(imageUrl, new SoftReference<Drawable>(drawable)); Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); } }.start(); return null; }
public static Bitmap loadBitmap(String url, UrlBitmapDownloadCallback callback) { if (TextUtils.isEmpty(url)) { return null; } SoftReference<Bitmap> sf = mapUrlToBitmap.get(url); Bitmap bmp = null; if (sf != null) { bmp = sf.get(); } if (bmp == null) { String filePath = FilePaths.getUrlFileCachePath(url); if (new File(filePath).exists()) { BitmapFactory.Options op = new BitmapFactory.Options(); SystemUtils.computeSampleSize(op, filePath, 1024, 1024 * 512); try { bmp = BitmapFactory.decodeFile(filePath, op); } catch (OutOfMemoryError e) { e.printStackTrace(); op.inSampleSize *= 2; bmp = BitmapFactory.decodeFile(filePath, op); } } if (bmp == null) { if (callback != null) { mapUrlToCallback.put(url, callback); } requestDownloadBitmap(url, filePath); } else if (bmp != null) { mapUrlToBitmap.put(url, new SoftReference<Bitmap>(bmp)); } } return bmp; }
/** * 从缓存中获取图片 * * @param url * @return */ public Bitmap getBitmapFromCache(String url) { Bitmap bitmap; // 先从硬引用缓存获取数据 synchronized (mLruCache) { bitmap = mLruCache.get(url); if (bitmap != null) { // 如果找到的话,把元素移到LinkedHashMap的最前面,从而保证在LRU算法中是最后被删除 mLruCache.remove(url); mLruCache.put(url, bitmap); return bitmap; } } // 如果硬引用缓存找不到数据,进入软引用缓存 synchronized (mSoftCache) { SoftReference<Bitmap> bitmapReference = mSoftCache.get(url); if (bitmapReference != null) { bitmap = bitmapReference.get(); if (bitmap != null) { // 将图片移回硬缓存 mLruCache.put(url, bitmap); mSoftCache.remove(url); return bitmap; } else { mSoftCache.remove(url); } } } return null; }
@Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder vh = (ViewHolder) view.getTag(); if (vh == null || !(view instanceof XboxLiveFriendListItem)) return; XboxLiveFriendListItem friend = (XboxLiveFriendListItem) view; friend.mFriendId = cursor.getLong(0); friend.mStatusCode = cursor.getInt(COLUMN_STATUS_CODE); friend.mGamertag = cursor.getString(COLUMN_GAMERTAG); friend.mIsFavorite = (cursor.getInt(COLUMN_IS_FAVORITE) != 0); friend.mClickListener = FriendsFragment.this; vh.gamertag.setText(cursor.getString(COLUMN_GAMERTAG)); vh.currentActivity.setText(cursor.getString(COLUMN_ACTIVITY)); vh.gamerscore.setText(context.getString(R.string.x_f, cursor.getInt(COLUMN_POINTS))); String iconUrl = cursor.getString(COLUMN_ICON_URL); SoftReference<Bitmap> icon = mIconCache.get(iconUrl); if (icon != null && icon.get() != null) { // Image is in the in-memory cache vh.avatar.setImageBitmap(icon.get()); } else { // Image has likely been garbage-collected // Load it into the cache again Bitmap bmp = ImageCache.getInstance().getCachedBitmap(iconUrl); if (bmp != null) { mIconCache.put(iconUrl, new SoftReference<Bitmap>(bmp)); vh.avatar.setImageBitmap(bmp); } else { // Image failed to load - just use placeholder vh.avatar.setImageResource(R.drawable.avatar_default); } } iconUrl = cursor.getString(COLUMN_TITLE_ICON_URL); icon = mIconCache.get(iconUrl); if (icon != null && icon.get() != null) { // Image is in the in-memory cache vh.titleIcon.setImageBitmap(icon.get()); } else { // Image has likely been garbage-collected // Load it into the cache again Bitmap bmp = ImageCache.getInstance().getCachedBitmap(iconUrl); if (bmp != null) { mIconCache.put(iconUrl, new SoftReference<Bitmap>(bmp)); vh.titleIcon.setImageBitmap(bmp); } else { // Image failed to load - just use placeholder vh.titleIcon.setImageResource(R.drawable.xbox_game_empty_boxart); } } vh.isFavorite.setImageResource( friend.mIsFavorite ? R.drawable.favorite_on : R.drawable.favorite_off); }
/** * 获取图片(一级缓存) * * @param dirFile : 缓存目录 * @param url : 图片路径 */ public static Bitmap getBitmap( Activity activity, File dirFile, String url, boolean isRequestNet) { System.out.println("BitmapUtil.getBitmap()"); SoftReference<Bitmap> softReference = bitmapCaches.get(MD5.getMessageDigest(url)); return softReference != null ? softReference.get() : getLocalBitmap(activity, dirFile, url, isRequestNet); }
private static Object deref(ThreadLocal tl) { SoftReference sr = (SoftReference) tl.get(); if (sr == null) return null; return sr.get(); }
@Override public Bitmap get(String key) { SoftReference<Bitmap> memBitmap = mMemoryCache.get(key); if (memBitmap != null) { return memBitmap.get(); } return null; }
public Object get(Object key) { SoftReference ref = (SoftReference) map.get(key); if (ref == null) { return null; } else { return ref.get(); } }
public V get(Object key) { processQueue(); SoftReference<V> o = map.get(key); if (o == null) { return null; } return o.get(); }