Java Code Examples for java.lang.ref.SoftReference

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project clojure, under directory /src/jvm/clojure/lang/.

Source file: DynamicClassLoader.java

  18 
vote

public Class defineClass(String name,byte[] bytes,Object srcForm){
  Util.clearCache(rq,classCache);
  Class c=defineClass(name,bytes,0,bytes.length);
  classCache.put(name,new SoftReference(c,rq));
  return c;
}
 

Example 2

From project javassist, under directory /src/main/javassist/scopedpool/.

Source file: SoftValueHashMap.java

  18 
vote

/** 
 * Returns the value to which this map maps the specified <code>key</code>. If this map does not contain a value for this key, then return <code>null</code>.
 * @param key The key whose associated value, if any, is to be returned.
 */
public Object get(Object key){
  processQueue();
  SoftReference ref=(SoftReference)hash.get(key);
  if (ref != null)   return ref.get();
  return null;
}
 

Example 3

From project jmd, under directory /src/org/apache/bcel/util/.

Source file: SyntheticRepository.java

  18 
vote

/** 
 * Find an already defined (cached) JavaClass object by name.
 */
public JavaClass findClass(String className){
  SoftReference ref=(SoftReference)_loadedClasses.get(className);
  if (ref == null) {
    return null;
  }
  return (JavaClass)ref.get();
}
 

Example 4

From project makegood, under directory /com.piece_framework.makegood.aspect/lib/javassist-3.11.0/src/main/javassist/scopedpool/.

Source file: SoftValueHashMap.java

  18 
vote

/** 
 * Returns the value to which this map maps the specified <code>key</code>. If this map does not contain a value for this key, then return <code>null</code>.
 * @param key The key whose associated value, if any, is to be returned.
 */
public Object get(Object key){
  processQueue();
  SoftReference ref=(SoftReference)hash.get(key);
  if (ref != null)   return ref.get();
  return null;
}
 

Example 5

From project platform_external_javassist, under directory /src/main/javassist/scopedpool/.

Source file: SoftValueHashMap.java

  18 
vote

/** 
 * Returns the value to which this map maps the specified <code>key</code>. If this map does not contain a value for this key, then return <code>null</code>.
 * @param key The key whose associated value, if any, is to be returned.
 */
public Object get(Object key){
  processQueue();
  SoftReference ref=(SoftReference)hash.get(key);
  if (ref != null)   return ref.get();
  return null;
}
 

Example 6

From project Custom-Salem, under directory /src/haven/.

Source file: JarSignersHardLinker.java

  17 
vote

/** 
 * if the specified field for the given instance is a Softreference That soft reference is resolved and the returned ref is stored in a static list, making it a hard link that should never be garbage collected
 * @param fieldName
 * @param instance
 */
private static void makeHardLink(String fieldName,Object instance){
  System.out.println("attempting hard ref to " + instance.getClass().getName() + "."+ fieldName);
  try {
    Field signersRef=instance.getClass().getDeclaredField(fieldName);
    signersRef.setAccessible(true);
    Object o=signersRef.get(instance);
    if (o instanceof SoftReference) {
      SoftReference r=(SoftReference)o;
      Object o2=r.get();
      sm_hardRefs.add(o2);
    }
 else {
      System.out.println("noooo!");
    }
  }
 catch (  NoSuchFieldException e) {
    e.printStackTrace();
    return;
  }
catch (  IllegalAccessException e) {
    e.printStackTrace();
  }
}
 

Example 7

From project eclipse.platform.runtime, under directory /bundles/org.eclipse.core.contenttype/src/org/eclipse/core/internal/content/.

Source file: ContentTypeHandler.java

  17 
vote

/** 
 * Returns the content type this handler represents.  Note that this handles the case of aliasing. Public for testing purposes only.
 */
public ContentType getTarget(){
  ContentType target=(ContentType)targetRef.get();
  ContentTypeCatalog catalog=ContentTypeManager.getInstance().getCatalog();
  if (target == null || catalog.getGeneration() != generation) {
    target=catalog.getContentType(id);
    targetRef=new SoftReference(target);
    generation=catalog.getGeneration();
  }
  return target == null ? null : target.getAliasTarget(true);
}
 

Example 8

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/pagelet/.

Source file: Pagelet.java

  17 
vote

/** 
 * Opens an input stream of the pagelet from the cache.
 * @return the input stream of the pagelet.
 * @throws IOException if unable to create a new input stream.
 */
private synchronized InputStream openStreamFromCache() throws IOException {
  byte[] cache=(byte[])(content == null ? null : content.get());
  if (cache == null) {
    InputStream ins=pagelet.openStream();
    byte[] bytes=IOHandler.readBytes(ins);
    content=new SoftReference(bytes);
    cache=bytes;
  }
  return new ByteArrayInputStream(cache);
}
 

Example 9

From project jetty-session-redis, under directory /src/main/java/com/ovea/jetty/session/serializer/jboss/serial/references/.

Source file: PersistentReference.java

  17 
vote

/** 
 * This method should be called from a synchronized block
 */
protected void buildReference(Object obj){
  if (obj == null) {
    referencedObject=null;
  }
 else {
    if (referenceType == REFERENCE_WEAK) {
      referencedObject=new WeakReference(obj);
    }
 else {
      referencedObject=new SoftReference(obj);
    }
  }
}
 

Example 10

From project Json-lib, under directory /src/main/java/net/sf/json/.

Source file: AbstractJSON.java

  17 
vote

public Set getSet(){
  Set set=(Set)((SoftReference)get()).get();
  if (set == null) {
    set=new HashSet();
    set(new SoftReference(set));
  }
  return set;
}
 

Example 11

From project jumpnevolve, under directory /lib/slick/src/org/newdawn/slick/opengl/.

Source file: InternalTextureLoader.java

  17 
vote

/** 
 * Get a texture from a image file
 * @param in The stream from which we can load the image
 * @param resourceName The name to give this image in the internal cache
 * @param flipped True if we should flip the image on the y-axis while loading
 * @param filter The filter to use when scaling the texture
 * @param transparent The colour to interpret as transparent or null if none
 * @return The texture loaded
 * @throws IOException Indicates a failure to load the image
 */
public TextureImpl getTexture(InputStream in,String resourceName,boolean flipped,int filter,int[] transparent) throws IOException {
  if (deferred) {
    return new DeferredTexture(in,resourceName,flipped,filter,transparent);
  }
  HashMap hash=texturesLinear;
  if (filter == GL11.GL_NEAREST) {
    hash=texturesNearest;
  }
  String resName=resourceName;
  if (transparent != null) {
    resName+=":" + transparent[0] + ":"+ transparent[1]+ ":"+ transparent[2];
  }
  resName+=":" + flipped;
  SoftReference ref=(SoftReference)hash.get(resName);
  if (ref != null) {
    TextureImpl tex=(TextureImpl)ref.get();
    if (tex != null) {
      return tex;
    }
 else {
      hash.remove(resName);
    }
  }
  try {
    GL11.glGetError();
  }
 catch (  NullPointerException e) {
    throw new RuntimeException("Image based resources must be loaded as part of init() or the game loop. They cannot be loaded before initialisation.");
  }
  TextureImpl tex=getTexture(in,resourceName,GL11.GL_TEXTURE_2D,filter,filter,flipped,transparent);
  tex.setCacheName(resName);
  hash.put(resName,new SoftReference(tex));
  return tex;
}
 

Example 12

From project mchange-commons-java, under directory /src/java/com/mchange/util/impl/.

Source file: SoftReferenceObjectCache.java

  17 
vote

public synchronized Object find(Object key) throws Exception {
  Reference ref=(Reference)store.get(key);
  Object out;
  if (ref == null || (out=ref.get()) == null || isDirty(key,out)) {
    out=createFromKey(key);
    store.put(key,new SoftReference(out));
  }
  return out;
}
 

Example 13

From project phing-eclipse, under directory /org.ganoro.phing.ui/src/org/ganoro/phing/ui/internal/dtd/util/.

Source file: Factory.java

  17 
vote

private Head getHead(){
  Head head=(Head)free.get();
  if (head == null) {
    head=new Head();
    free=new SoftReference(head);
  }
  return head;
}
 

Example 14

From project commons-pool, under directory /src/java/org/apache/commons/pool/impl/.

Source file: SoftReferenceObjectPool.java

  16 
vote

/** 
 * <p>Returns an instance to the pool after successful validation and passivation. The returning instance is destroyed if any of the following are true:<ul> <li>the pool is closed</li> <li> {@link PoolableObjectFactory#validateObject(Object) validation} fails</li><li> {@link PoolableObjectFactory#passivateObject(Object) passivation} throws an exception</li></ul> </p> <p>Exceptions passivating or destroying instances are silently swallowed.  Exceptions validating instances are propagated to the client.</p>
 * @param obj instance to return to the pool
 */
public synchronized void returnObject(Object obj) throws Exception {
  boolean success=!isClosed();
  if (_factory != null) {
    if (!_factory.validateObject(obj)) {
      success=false;
    }
 else {
      try {
        _factory.passivateObject(obj);
      }
 catch (      Exception e) {
        success=false;
      }
    }
  }
  boolean shouldDestroy=!success;
  _numActive--;
  if (success) {
    _pool.add(new SoftReference(obj,refQueue));
  }
  notifyAll();
  if (shouldDestroy && _factory != null) {
    try {
      _factory.destroyObject(obj);
    }
 catch (    Exception e) {
    }
  }
}
 

Example 15

From project Alerte-voirie-android, under directory /src/com/c4mprod/utils/.

Source file: ImageDownloader.java

  15 
vote

/** 
 * @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){
  if (mExternalStorageAvailable && url != null) {
    File f=new File(mfolder,URLEncoder.encode(url));
    if (f.exists()) {
      try {
        return BitmapFactory.decodeFile(f.getPath());
      }
 catch (      Exception e) {
        e.printStackTrace();
      }
    }
  }
synchronized (sHardBitmapCache) {
    final Bitmap bitmap=sHardBitmapCache.get(url);
    if (bitmap != null) {
      sHardBitmapCache.remove(url);
      sHardBitmapCache.put(url,bitmap);
      return bitmap;
    }
  }
  try {
    SoftReference<Bitmap> bitmapReference=sSoftBitmapCache.get(url);
    if (bitmapReference != null) {
      final Bitmap bitmap=bitmapReference.get();
      if (bitmap != null) {
        return bitmap;
      }
 else {
        sSoftBitmapCache.remove(url);
      }
    }
  }
 catch (  Exception e) {
    return null;
  }
  return null;
}
 

Example 16

From project AmDroid, under directory /AmDroid/src/main/java/com/jaeckel/amenoid/cwac/bus/.

Source file: AbstractBus.java

  15 
vote

public void unregister(Receiver receiver,BlockingQueue<SoftReference<M>> q){
  for (  Registration r : regs) {
    if (r.receiver == receiver) {
synchronized (r) {
        if (q == null) {
          regs.remove(r);
        }
 else {
          r.setQueue(q);
        }
      }
    }
  }
}
 

Example 17

From project Android-File-Manager, under directory /src/com/nexes/manager/.

Source file: ThumbnailCreator.java

  15 
vote

@Override public void run(){
  int len=mFiles.size();
  for (int i=0; i < len; i++) {
    if (mStop) {
      mStop=false;
      mFiles=null;
      return;
    }
    final File file=new File(mDir + "/" + mFiles.get(i));
    if (isImageFile(file.getName())) {
      long len_kb=file.length() / 1024;
      BitmapFactory.Options options=new BitmapFactory.Options();
      options.outWidth=mWidth;
      options.outHeight=mHeight;
      if (len_kb > 1000 && len_kb < 5000) {
        options.inSampleSize=32;
        options.inPurgeable=true;
        mThumb=new SoftReference<Bitmap>(BitmapFactory.decodeFile(file.getPath(),options));
      }
 else       if (len_kb >= 5000) {
        options.inSampleSize=32;
        options.inPurgeable=true;
        mThumb=new SoftReference<Bitmap>(BitmapFactory.decodeFile(file.getPath(),options));
      }
 else       if (len_kb <= 1000) {
        options.inPurgeable=true;
        mThumb=new SoftReference<Bitmap>(Bitmap.createScaledBitmap(BitmapFactory.decodeFile(file.getPath()),mWidth,mHeight,false));
      }
      mCacheMap.put(file.getPath(),mThumb.get());
      mHandler.post(new Runnable(){
        @Override public void run(){
          Message msg=mHandler.obtainMessage();
          msg.obj=(Bitmap)mThumb.get();
          msg.sendToTarget();
        }
      }
);
    }
  }
}
 

Example 18

From project android-joedayz, under directory /Proyectos/GreenDroid/src/greendroid/image/.

Source file: ImageCache.java

  15 
vote

public Bitmap get(String url){
  final SoftReference<Bitmap> ref=mSoftCache.get(url);
  if (ref == null) {
    return null;
  }
  final Bitmap bitmap=ref.get();
  if (bitmap == null) {
    mSoftCache.remove(url);
  }
  return bitmap;
}
 

Example 19

From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/core/util/.

Source file: DateUtils.java

  15 
vote

@Override public SoftReference<DateFormat> get(){
  SoftReference<DateFormat> value=super.get();
  if (value == null || value.get() == null) {
    value=createValue();
    set(value);
  }
  return value;
}
 

Example 20

From project android-thaiime, under directory /latinime/src/com/android/inputmethod/keyboard/.

Source file: KeyboardSwitcher.java

  15 
vote

private LatinKeyboard getKeyboard(KeyboardId id){
  final SoftReference<LatinKeyboard> ref=mKeyboardCache.get(id);
  LatinKeyboard keyboard=(ref == null) ? null : ref.get();
  if (keyboard == null) {
    final Locale savedLocale=LocaleUtils.setSystemLocale(mResources,id.mLocale);
    try {
      final LatinKeyboard.Builder builder=new LatinKeyboard.Builder(mThemeContext);
      builder.load(id);
      builder.setTouchPositionCorrectionEnabled(mSubtypeSwitcher.currentSubtypeContainsExtraValueKey(LatinIME.SUBTYPE_EXTRA_VALUE_SUPPORT_TOUCH_POSITION_CORRECTION));
      keyboard=builder.build();
    }
  finally {
      LocaleUtils.setSystemLocale(mResources,savedLocale);
    }
    mKeyboardCache.put(id,new SoftReference<LatinKeyboard>(keyboard));
    if (DEBUG_CACHE) {
      Log.d(TAG,"keyboard cache size=" + mKeyboardCache.size() + ": "+ ((ref == null) ? "LOAD" : "GCed")+ " id="+ id+ " theme="+ Keyboard.themeName(keyboard.mThemeId));
    }
  }
 else   if (DEBUG_CACHE) {
    Log.d(TAG,"keyboard cache size=" + mKeyboardCache.size() + ": HIT  id="+ id+ " theme="+ Keyboard.themeName(keyboard.mThemeId));
  }
  keyboard.onAutoCorrectionStateChanged(mIsAutoCorrectionActive);
  keyboard.setShiftLocked(false);
  keyboard.setShifted(false);
  keyboard.setSpacebarTextFadeFactor(0.0f,null);
  keyboard.updateShortcutKey(mSubtypeSwitcher.isShortcutImeReady(),null);
  return keyboard;
}
 

Example 21

From project android-wheel, under directory /wheel-demo/src/kankan/wheel/demo/.

Source file: SlotMachineActivity.java

  15 
vote

/** 
 * Constructor
 */
public SlotMachineAdapter(Context context){
  this.context=context;
  images=new ArrayList<SoftReference<Bitmap>>(items.length);
  for (  int id : items) {
    images.add(new SoftReference<Bitmap>(loadImage(id)));
  }
}
 

Example 22

From project android-wheel_1, under directory /wheel-demo/src/kankan/wheel/demo/.

Source file: SlotMachineActivity.java

  15 
vote

/** 
 * Constructor
 */
public SlotMachineAdapter(Context context){
  this.context=context;
  images=new ArrayList<SoftReference<Bitmap>>(items.length);
  for (  int id : items) {
    images.add(new SoftReference<Bitmap>(loadImage(id)));
  }
}
 

Example 23

From project android-xbmcremote, under directory /src/org/xbmc/android/remote/business/.

Source file: MemCacheThread.java

  15 
vote

/** 
 * Asynchronously returns a thumb from the mem cache, or null if  not available.
 * @param response Response object
 * @param cover   Which cover to return
 */
public void getCover(final DataResponse<Bitmap> response,final ICoverArt cover,final int thumbSize,final INotifiableController controller,final Bitmap defaultCover){
  if (controller == null) {
    Log.w(TAG,"[" + cover.getId() + "] Controller is null.");
  }
  mHandler.post(new Runnable(){
    public void run(){
      if (DEBUG)       Log.i(TAG,"[" + cover.getId() + "] Checking if cover in cache..");
      if (cover != null) {
        final long crc=cover.getCrc();
        final SoftReference<Bitmap> ref=getCache(thumbSize).get(crc);
        if (ref != null) {
          if (DEBUG)           Log.i(TAG,"[" + cover.getId() + "] -> In cache.");
          response.value=ref.get();
          if (DEBUG && response.value == null)           Log.w(TAG,"[" + cover.getId() + "] -> GC'd from cache.");
        }
 else         if (sNotAvailable.containsKey(crc)) {
          if (DEBUG)           Log.i(TAG,"[" + cover.getId() + "] -> Marked as not-in-cache ("+ crc+ ").");
          response.value=defaultCover;
        }
 else {
          if (DEBUG)           Log.i(TAG,"[" + cover.getId() + "] -> Not in cache.");
        }
      }
      done(controller,response);
    }
  }
);
}
 

Example 24

From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/util/.

Source file: ImageUtilities.java

  15 
vote

/** 
 * Retrieves a drawable from the book covers cache, identified by the specified id. If the drawable does not exist in the cache, it is loaded and added to the cache. If the drawable cannot be added to the cache, the specified default drwaable is returned.
 * @param id The id of the drawable to retrieve
 * @param defaultCover The default drawable returned if no drawable can be found thatmatches the id
 * @return The drawable identified by id or defaultCover
 */
public static FastBitmapDrawable getCachedCover(String id,FastBitmapDrawable defaultCover){
  FastBitmapDrawable drawable=null;
  SoftReference<FastBitmapDrawable> reference=sArtCache.get(id);
  if (reference != null) {
    drawable=reference.get();
  }
  if (drawable == null) {
    final Bitmap bitmap=loadCover(id);
    if (bitmap != null) {
      drawable=new FastBitmapDrawable(bitmap);
    }
 else {
      drawable=NULL_DRAWABLE;
    }
    sArtCache.put(id,new SoftReference<FastBitmapDrawable>(drawable));
  }
  return drawable == NULL_DRAWABLE ? defaultCover : drawable;
}
 

Example 25

From project android_7, under directory /src/org/immopoly/android/helper/.

Source file: ImageListDownloader.java

  15 
vote

@Override protected boolean removeEldestEntry(Map.Entry<String,Bitmap> eldest){
  if (size() > HARD_CACHE_CAPACITY) {
    sSoftBitmapCache.put(eldest.getKey(),new SoftReference<Bitmap>(eldest.getValue()));
    return true;
  }
 else   return false;
}
 

Example 26

From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/.

Source file: ThumbnailLoader.java

  15 
vote

/** 
 * Used for loading and decoding thumbnails from files.
 * @author PhilipHayes
 * @param context Current application context.
 */
public ThumbnailLoader(Context context){
  mContext=context;
  purger=new Runnable(){
    @Override public void run(){
      Log.d(TAG,"Purge Timer hit; Clearing Caches.");
      clearCaches();
    }
  }
;
  purgeHandler=new Handler();
  mExecutor=Executors.newFixedThreadPool(POOL_SIZE);
  mBlacklist=new ArrayList<String>();
  mSoftBitmapCache=new ConcurrentHashMap<String,SoftReference<Bitmap>>(MAX_CACHE_CAPACITY / 2);
  mHardBitmapCache=new LinkedHashMap<String,Bitmap>(MAX_CACHE_CAPACITY / 2,0.75f,true){
    /** 
 */
    private static final long serialVersionUID=1347795807259717646L;
    @Override protected boolean removeEldestEntry(    LinkedHashMap.Entry<String,Bitmap> eldest){
      if (size() > MAX_CACHE_CAPACITY) {
        mSoftBitmapCache.put(eldest.getKey(),new SoftReference<Bitmap>(eldest.getValue()));
        return true;
      }
 else {
        return false;
      }
    }
  }
;
}
 

Example 27

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/data/.

Source file: LocalMergeAlbum.java

  15 
vote

public MediaItem getItem(int index){
  boolean needLoading=false;
  ArrayList<MediaItem> cache=null;
  if (mCacheRef == null || index < mStartPos || index >= mStartPos + PAGE_SIZE) {
    needLoading=true;
  }
 else {
    cache=mCacheRef.get();
    if (cache == null) {
      needLoading=true;
    }
  }
  if (needLoading) {
    cache=mBaseSet.getMediaItem(index,PAGE_SIZE);
    mCacheRef=new SoftReference<ArrayList<MediaItem>>(cache);
    mStartPos=index;
  }
  if (index < mStartPos || index >= mStartPos + cache.size()) {
    return null;
  }
  return cache.get(index - mStartPos);
}
 

Example 28

From project android_packages_inputmethods_LatinIME, under directory /java/src/com/android/inputmethod/keyboard/.

Source file: KeyboardSwitcher.java

  15 
vote

private LatinKeyboard getKeyboard(KeyboardId id){
  final SoftReference<LatinKeyboard> ref=mKeyboardCache.get(id);
  LatinKeyboard keyboard=(ref == null) ? null : ref.get();
  if (keyboard == null) {
    final Locale savedLocale=LocaleUtils.setSystemLocale(mResources,id.mLocale);
    try {
      final LatinKeyboard.Builder builder=new LatinKeyboard.Builder(mThemeContext);
      builder.load(id);
      builder.setTouchPositionCorrectionEnabled(mSubtypeSwitcher.currentSubtypeContainsExtraValueKey(LatinIME.SUBTYPE_EXTRA_VALUE_SUPPORT_TOUCH_POSITION_CORRECTION));
      keyboard=builder.build();
    }
  finally {
      LocaleUtils.setSystemLocale(mResources,savedLocale);
    }
    mKeyboardCache.put(id,new SoftReference<LatinKeyboard>(keyboard));
    if (DEBUG_CACHE) {
      Log.d(TAG,"keyboard cache size=" + mKeyboardCache.size() + ": "+ ((ref == null) ? "LOAD" : "GCed")+ " id="+ id+ " theme="+ Keyboard.themeName(keyboard.mThemeId));
    }
  }
 else   if (DEBUG_CACHE) {
    Log.d(TAG,"keyboard cache size=" + mKeyboardCache.size() + ": HIT  id="+ id+ " theme="+ Keyboard.themeName(keyboard.mThemeId));
  }
  keyboard.onAutoCorrectionStateChanged(mIsAutoCorrectionActive);
  keyboard.setShiftLocked(false);
  keyboard.setShifted(false);
  keyboard.setSpacebarTextFadeFactor(0.0f,null);
  keyboard.updateShortcutKey(mSubtypeSwitcher.isShortcutImeReady(),null);
  return keyboard;
}
 

Example 29

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/corecomponents/.

Source file: ThumbnailViewNode.java

  15 
vote

@Override public Image getIcon(int type){
  Image icon=null;
  if (iconCache != null) {
    icon=iconCache.get();
  }
  if (icon == null) {
    Content content=this.getLookup().lookup(Content.class);
    if (content != null) {
      if (getFile(content.getId()).exists()) {
        try {
          icon=ImageIO.read(getFile(content.getId()));
        }
 catch (        IOException ex) {
          icon=ThumbnailViewNode.defaultIcon;
        }
      }
 else {
        try {
          icon=generateIcon(content);
          ImageIO.write(toBufferedImage(icon),"jpg",getFile(content.getId()));
        }
 catch (        TskException ex) {
          icon=ThumbnailViewNode.defaultIcon;
        }
catch (        IOException ex) {
        }
      }
    }
 else {
      icon=ThumbnailViewNode.defaultIcon;
    }
    iconCache=new SoftReference<Image>(icon);
  }
  return icon;
}
 

Example 30

From project be.norio.twunch.android, under directory /src/com/koushikdutta/urlimageviewhelper/.

Source file: SoftReferenceHashTable.java

  15 
vote

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;
}
 

Example 31

From project beanvalidation-api, under directory /src/test/java/javax/validation/.

Source file: ValidationTest.java

  15 
vote

private int countInMemoryProviders(){
  int count=0;
  for (  SoftReference<DummyValidationProvider> ref : DummyValidationProvider.createdValidationProviders) {
    if (ref.get() != null) {
      count++;
    }
  }
  return count;
}
 

Example 32

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: ImageManager.java

  15 
vote

@Override public void run(){
  try {
    while (true) {
      if (imageQueue.imageRefs.size() == 0) {
synchronized (imageQueue.imageRefs) {
          imageQueue.imageRefs.wait();
        }
      }
      if (imageQueue.imageRefs.size() != 0) {
        ImageRef imageToLoad;
synchronized (imageQueue.imageRefs) {
          imageToLoad=imageQueue.imageRefs.pop();
        }
        Bitmap bmp=getBitmap(imageToLoad.url);
        imageMap.put(imageToLoad.url,new SoftReference<Bitmap>(bmp));
        Object tag=imageToLoad.imageView.getTag();
        if (tag != null && ((String)tag).equals(imageToLoad.url)) {
          BitmapDisplayer bmpDisplayer=new BitmapDisplayer(bmp,imageToLoad.imageView);
          UIhandler.post(bmpDisplayer);
        }
      }
      if (Thread.interrupted())       break;
    }
  }
 catch (  InterruptedException e) {
    if (debug)     e.printStackTrace();
  }
}
 

Example 33

From project bioportal-service, under directory /src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/transform/.

Source file: AbstractBioportalOntologyVersionTransformTemplate.java

  15 
vote

private static DateFormat getDateFormat(){
  SoftReference<DateFormat> ref=threadLocal.get();
  if (ref != null) {
    DateFormat result=ref.get();
    if (result != null) {
      return result;
    }
  }
  DateFormat result=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S zzz");
  ref=new SoftReference<DateFormat>(result);
  threadLocal.set(ref);
  return result;
}
 

Example 34

From project Birthday-widget, under directory /Birthday/src/main/java/cz/krtinec/birthday/ui/.

Source file: StockPhotoLoader.java

  15 
vote

/** 
 * Stores the supplied bitmap in cache.
 */
private void cacheBitmap(long id,Drawable drawable){
  if (mPaused) {
    return;
  }
  BitmapHolder holder=new BitmapHolder();
  holder.state=BitmapHolder.LOADED;
  if (drawable != null) {
    try {
      holder.bitmapRef=new SoftReference<Drawable>(drawable);
    }
 catch (    OutOfMemoryError e) {
    }
  }
  mBitmapCache.put(id,holder);
}
 

Example 35

From project Blitz, under directory /src/com/laxser/blitz/scanning/.

Source file: BlitzScanner.java

  15 
vote

public synchronized static BlitzScanner getInstance(){
  if (softReference == null || softReference.get() == null) {
    BlitzScanner blitzScanner=new BlitzScanner();
    softReference=new SoftReference<BlitzScanner>(blitzScanner);
  }
  return softReference.get();
}
 

Example 36

From project BreizhCamp-android, under directory /src/org/breizhjug/breizhcamp/util/.

Source file: ImageLoader.java

  15 
vote

public void run(){
  try {
    while (true) {
      if (photosQueue.photosToLoad.size() == 0) synchronized (photosQueue.photosToLoad) {
        photosQueue.photosToLoad.wait();
      }
      if (photosQueue.photosToLoad.size() != 0) {
        PhotoToLoad photoToLoad;
synchronized (photosQueue.photosToLoad) {
          photoToLoad=photosQueue.photosToLoad.pop();
        }
        Bitmap bmp=getBitmap(photoToLoad.url,photoToLoad.sig);
        cache.put(photoToLoad.url,new SoftReference<Bitmap>(bmp));
        BitmapDisplayer bd=new BitmapDisplayer(bmp,photoToLoad.imageView);
        Activity a=(Activity)photoToLoad.imageView.getContext();
        a.runOnUiThread(bd);
      }
      if (Thread.interrupted())       break;
    }
  }
 catch (  InterruptedException e) {
  }
}
 

Example 37

From project bson4jackson, under directory /src/main/java/de/undercouch/bson4jackson/io/.

Source file: StaticBuffers.java

  15 
vote

/** 
 * @return a thread-local singleton instance of this class
 */
public static StaticBuffers getInstance(){
  SoftReference<StaticBuffers> ref=_instance.get();
  StaticBuffers buf=(ref == null ? null : ref.get());
  if (buf == null) {
    buf=new StaticBuffers();
    _instance.set(new SoftReference<StaticBuffers>(buf));
  }
  return buf;
}
 

Example 38

From project CineShowTime-Android, under directory /Libraries/CineShowTime/src/com/binomed/showtime/android/util/images/.

Source file: ImageDownloader.java

  15 
vote

/** 
 * @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){
synchronized (sHardBitmapCache) {
    final Bitmap bitmap=sHardBitmapCache.get(url);
    if (bitmap != null) {
      sHardBitmapCache.remove(url);
      sHardBitmapCache.put(url,bitmap);
      return bitmap;
    }
  }
  SoftReference<Bitmap> bitmapReference=sSoftBitmapCache.get(url);
  if (bitmapReference != null) {
    final Bitmap bitmap=bitmapReference.get();
    if (bitmap != null) {
      return bitmap;
    }
 else {
      sSoftBitmapCache.remove(url);
    }
  }
  return null;
}
 

Example 39

From project closure-templates, under directory /java/src/com/google/template/soy/javasrc/dyncompile/.

Source file: ClasspathUtils.java

  15 
vote

/** 
 * Returns a mapping from package paths (e.g.  {@code "java/lang"}) to the contents of that package that are findable from the  {@code URLClassLoader}s.
 */
private static Map<String,PackageContent> getPackagePathToContentMap(){
  Map<String,PackageContent> packagePathToContentMap=null;
  if (packagePathToContentMapRef != null) {
    packagePathToContentMap=packagePathToContentMapRef.get();
  }
  if (packagePathToContentMap == null) {
    packagePathToContentMap=buildPackagePathToContentMapFromURLClassLoaders(CLASS_LOADER);
    packagePathToContentMapRef=new SoftReference<Map<String,PackageContent>>(packagePathToContentMap);
  }
  return packagePathToContentMap;
}
 

Example 40

From project CMM-data-grabber, under directory /paul/src/main/java/au/edu/uq/cmm/paul/status/.

Source file: FacilitySessionCache.java

  15 
vote

public synchronized FacilitySession lookup(long time){
  tidy();
  Map.Entry<Long,SoftReference<FacilitySession>> entry=cache.floorEntry(time);
  if (entry != null) {
    FacilitySession session=entry.getValue().get();
    if (session != null && session.getInferredLogoutTime().getTime() >= time) {
      return session;
    }
  }
  return null;
}
 

Example 41

From project CommunityCase, under directory /src/org/community/intellij/plugins/communitycase/i18n/.

Source file: Bundle.java

  15 
vote

private static ResourceBundle getBundle(){
  ResourceBundle bundle=null;
  if (ourBundle != null)   bundle=ourBundle.get();
  if (bundle == null) {
    bundle=ResourceBundle.getBundle(BUNDLE);
    ourBundle=new SoftReference<ResourceBundle>(bundle);
  }
  return bundle;
}
 

Example 42

From project D2-Java-Persistence, under directory /src/main/java/org/nkts/util/.

Source file: SoftHashMap.java

  15 
vote

public V get(Object key){
  V result=null;
  SoftReference<V> soft_ref=(SoftReference<V>)hash.get(key);
  if (soft_ref != null) {
    result=soft_ref.get();
    if (result == null) {
      hash.remove(key);
    }
 else {
      hardCache.addFirst(result);
      if (hardCache.size() > HARD_SIZE) {
        hardCache.removeLast();
      }
    }
  }
  return result;
}
 

Example 43

From project daisy-android-common, under directory /src/com/daisyworks/android/widget/.

Source file: ImageDownloader.java

  15 
vote

/** 
 * @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(final String url){
synchronized (sHardBitmapCache) {
    final Bitmap bitmap=sHardBitmapCache.get(url);
    if (bitmap != null) {
      sHardBitmapCache.remove(url);
      sHardBitmapCache.put(url,bitmap);
      return bitmap;
    }
  }
  SoftReference<Bitmap> bitmapReference=sSoftBitmapCache.get(url);
  if (bitmapReference != null) {
    final Bitmap bitmap=bitmapReference.get();
    if (bitmap != null) {
      return bitmap;
    }
 else {
      sSoftBitmapCache.remove(url);
    }
  }
  return null;
}
 

Example 44

From project dawn-ui, under directory /org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/swtxy/.

Source file: ImageTrace.java

  15 
vote

private AbstractDataset getDownsampled(AbstractDataset image){
  final int bin=getDownsampleBin();
  this.currentDownSampleBin=bin;
  if (bin == 1) {
    logger.trace("No downsample bin (or bin=1)");
    return image;
  }
  if (image.getDtype() != AbstractDataset.BOOL) {
    if (mipMap != null && mipMap.containsKey(bin) && mipMap.get(bin).get() != null) {
      logger.trace("Downsample bin used, " + bin);
      return (AbstractDataset)mipMap.get(bin).get();
    }
  }
 else {
    if (maskMap != null && maskMap.containsKey(bin) && maskMap.get(bin).get() != null) {
      logger.trace("Downsample mask bin used, " + bin);
      return (AbstractDataset)maskMap.get(bin).get();
    }
  }
  final Downsample downSampler=new Downsample(getDownsampleTypeDiamond(),new int[]{bin,bin});
  List<AbstractDataset> sets=downSampler.value(image);
  final AbstractDataset set=sets.get(0);
  if (image.getDtype() != AbstractDataset.BOOL) {
    if (mipMap == null)     mipMap=new HashMap<Integer,Reference<Object>>(3);
    mipMap.put(bin,new SoftReference<Object>(set));
    logger.trace("Downsample bin created, " + bin);
  }
 else {
    if (maskMap == null)     maskMap=new HashMap<Integer,Reference<Object>>(3);
    maskMap.put(bin,new SoftReference<Object>(set));
    logger.trace("Downsample mask bin created, " + bin);
  }
  return set;
}
 

Example 45

From project dcm4che, under directory /dcm4che-core/src/main/java/org/dcm4che/data/.

Source file: SpecificCharacterSet.java

  15 
vote

private static Encoder encoder(ThreadLocal<SoftReference<Encoder>> tl,Codec codec){
  SoftReference<Encoder> sr;
  Encoder enc;
  if ((sr=tl.get()) == null || (enc=sr.get()) == null || enc.codec != codec)   tl.set(new SoftReference<Encoder>(enc=new Encoder(codec)));
  return enc;
}
 

Example 46

From project DigitbooksExamples, under directory /DigitbooksExamples/src/fr/digitbooks/android/examples/chapitre06/.

Source file: AsynchronousListActivity.java

  15 
vote

public void run(){
  Bitmap bitmap=null;
  if (Thread.interrupted()) {
    return;
  }
  bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.avatar);
  try {
    Thread.sleep(RandomUtil.getPositiveInt(BACKGROUND_TASK_MIN_DURATION,BACKGROUND_TASK_MAX_DURATION));
  }
 catch (  InterruptedException e) {
    return;
  }
synchronized (mSoftCache) {
    mSoftCache.put(mImageId,new SoftReference<Bitmap>(bitmap));
  }
  final Message msg=new Message();
  msg.what=FETCH_IMAGE_MESSAGE;
  msg.arg1=mImageId;
  msg.obj=mImageView;
  mHandler.sendMessage(msg);
}
 

Example 47

From project DiscogsForAndroid, under directory /src/com/discogs/.

Source file: ImageDownloader.java

  15 
vote

/** 
 * @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){
synchronized (sHardBitmapCache) {
    final Bitmap bitmap=sHardBitmapCache.get(url);
    if (bitmap != null) {
      sHardBitmapCache.remove(url);
      sHardBitmapCache.put(url,bitmap);
      return bitmap;
    }
  }
  SoftReference<Bitmap> bitmapReference=sSoftBitmapCache.get(url);
  if (bitmapReference != null) {
    final Bitmap bitmap=bitmapReference.get();
    if (bitmap != null) {
      return bitmap;
    }
 else {
      sSoftBitmapCache.remove(url);
    }
  }
  return null;
}
 

Example 48

From project dozer, under directory /core/src/main/java/org/dozer/propertydescriptor/.

Source file: CustomGetSetPropertyDescriptor.java

  15 
vote

@Override public Method getWriteMethod() throws NoSuchMethodException {
  if (writeMethod == null || writeMethod.get() == null) {
    if (customSetMethod != null && !MappingUtils.isDeepMapping(fieldName)) {
      Method method=ReflectionUtils.findAMethod(clazz,customSetMethod);
      writeMethod=new SoftReference<Method>(method);
    }
 else {
      return super.getWriteMethod();
    }
  }
  return writeMethod.get();
}
 

Example 49

From project droidkit, under directory /src/org/droidkit/image/.

Source file: ImageCachingOperation.java

  15 
vote

public boolean saveToCache(Bitmap bitmap){
  memoryCache.put(cacheName,new SoftReference<Bitmap>(bitmap));
  try {
    if (bitmap != null) {
      File tempFile=new File(cacheFile + "-tmp");
      FileOutputStream cacheOut=new FileOutputStream(tempFile);
      bitmap.compress(CompressFormat.PNG,100,cacheOut);
      try {
        cacheOut.getFD().sync();
      }
 catch (      SyncFailedException e) {
      }
      cacheOut.close();
      if (cacheFile.canRead())       cacheFile.delete();
      tempFile.renameTo(cacheFile);
      Log.d(TAG,"Saved to cache " + cacheName);
      return true;
    }
  }
 catch (  IOException ioe) {
    Log.e(TAG,"Could save to cache " + cacheName,ioe);
  }
catch (  Exception e) {
    Log.e(TAG,"Could save to cache " + cacheName,e);
  }
  return false;
}
 

Example 50

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/feed/objects/.

Source file: AppObj.java

  15 
vote

private String getRenderableClause(){
  if (mRenderableClause != null) {
    String renderable=mRenderableClause.get();
    if (renderable != null) {
      return renderable;
    }
  }
  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;
}
 

Example 51

From project event-bus, under directory /src/main/java/com/northconcepts/eventbus/.

Source file: EventListenerStub.java

  15 
vote

public EventListenerStub(EventFilter filter,T listener,ReferenceQueue<? super T> referenceQueue){
  if (filter == null) {
    filter=EventFilter.NULL;
  }
  this.filter=filter;
  this.listener=new SoftReference<T>(listener,referenceQueue);
}
 

Example 52

From project fanfoudroid, under directory /src/com/ch_linghu/fanfoudroid/app/.

Source file: ImageManager.java

  15 
vote

public ImageManager(Context context){
  mContext=context;
  mCache=new HashMap<String,SoftReference<Bitmap>>();
  try {
    mDigest=MessageDigest.getInstance("MD5");
  }
 catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException("No MD5 algorithm.");
  }
}
 

Example 53

From project fasthat, under directory /src/com/sun/tools/hat/internal/model/.

Source file: Snapshot.java

  15 
vote

public synchronized Collection<JavaHeapObject> getFinalizerObjects(){
  if (finalizablesCache != null) {
    List<JavaHeapObject> obj=finalizablesCache.get();
    if (obj != null) {
      return obj;
    }
  }
  JavaClass clazz=findClass("java.lang.ref.Finalizer");
  JavaObject queue=(JavaObject)clazz.getStaticField("queue");
  JavaThing tmp=queue.getField("head");
  List<JavaHeapObject> finalizables=new ArrayList<JavaHeapObject>();
  if (tmp != getNullThing()) {
    JavaObject head=(JavaObject)tmp;
    while (true) {
      JavaHeapObject referent=(JavaHeapObject)head.getField("referent");
      JavaThing next=head.getField("next");
      if (next == getNullThing() || next.equals(head)) {
        break;
      }
      head=(JavaObject)next;
      finalizables.add(referent);
    }
  }
  finalizablesCache=new SoftReference<List<JavaHeapObject>>(finalizables);
  return finalizables;
}
 

Example 54

From project fastjson, under directory /src/main/java/com/alibaba/fastjson/parser/.

Source file: JSONScanner.java

  15 
vote

public JSONScanner(char[] input,int inputLength,int features){
  this.features=features;
  SoftReference<char[]> sbufRef=sbufRefLocal.get();
  if (sbufRef != null) {
    sbuf=sbufRef.get();
    sbufRefLocal.set(null);
  }
  if (sbuf == null) {
    sbuf=new char[64];
  }
  eofPos=inputLength;
  if (inputLength == input.length) {
    if (input.length > 0 && isWhitespace(input[input.length - 1])) {
      inputLength--;
    }
 else {
      char[] newInput=new char[inputLength + 1];
      System.arraycopy(input,0,newInput,0,input.length);
      input=newInput;
    }
  }
  buf=input;
  buflen=inputLength;
  buf[buflen]=EOI;
  bp=-1;
  ch=buf[++bp];
}
 

Example 55

From project filemanager, under directory /FileManager/src/org/openintents/filemanager/.

Source file: ThumbnailLoader.java

  15 
vote

/** 
 * Used for loading and decoding thumbnails from files.
 * @author PhilipHayes
 * @param context Current application context.
 */
public ThumbnailLoader(Context context){
  mContext=context;
  purger=new Runnable(){
    @Override public void run(){
      Log.d(TAG,"Purge Timer hit; Clearing Caches.");
      clearCaches();
    }
  }
;
  purgeHandler=new Handler();
  mExecutor=Executors.newFixedThreadPool(POOL_SIZE);
  mBlacklist=new ArrayList<String>();
  mSoftBitmapCache=new ConcurrentHashMap<String,SoftReference<Bitmap>>(MAX_CACHE_CAPACITY / 2);
  mHardBitmapCache=new LinkedHashMap<String,Bitmap>(MAX_CACHE_CAPACITY / 2,0.75f,true){
    /** 
 */
    private static final long serialVersionUID=1347795807259717646L;
    @Override protected boolean removeEldestEntry(    LinkedHashMap.Entry<String,Bitmap> eldest){
      if (size() > MAX_CACHE_CAPACITY) {
        mSoftBitmapCache.put(eldest.getKey(),new SoftReference<Bitmap>(eldest.getValue()));
        return true;
      }
 else {
        return false;
      }
    }
  }
;
}
 

Example 56

From project Flume-Hive, under directory /src/java/com/cloudera/util/.

Source file: Cache.java

  15 
vote

public V lookup(K key){
  SoftReference<V> val=map.get(key);
  if (val == null) {
    return null;
  }
  V v=val.get();
  if (v == null) {
    return null;
  }
  boolean ok=fifo.remove(key);
  assert(ok);
  fifo.addLast(key);
  return v;
}
 

Example 57

From project flume_1, under directory /flume-core/src/main/java/com/cloudera/util/.

Source file: Cache.java

  15 
vote

public V lookup(K key){
  SoftReference<V> val=map.get(key);
  if (val == null) {
    return null;
  }
  V v=val.get();
  if (v == null) {
    return null;
  }
  boolean ok=fifo.remove(key);
  assert(ok);
  fifo.addLast(key);
  return v;
}
 

Example 58

From project geronimo-xbean, under directory /xbean-classloader/src/main/java/org/apache/xbean/classloader/.

Source file: MultiParentClassLoader.java

  15 
vote

/** 
 * {@inheritDoc}
 */
protected Class loadClass(String name,boolean resolve) throws ClassNotFoundException {
  Class result=null;
  SoftReference<Class> reference=cache.get(name);
  if (reference != null) {
    result=reference.get();
  }
  if (result == null) {
    result=doLoadClass(name,resolve);
    cache.put(name,new SoftReference<Class>(result));
  }
  return result;
}
 

Example 59

From project Gingerbread-Keyboard, under directory /src/com/android/inputmethod/latin/.

Source file: KeyboardSwitcher.java

  15 
vote

public KeyboardSwitcher(LatinIME ims){
  mInputMethodService=ims;
  final SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(ims);
  mLayoutId=Integer.valueOf(prefs.getString(PREF_KEYBOARD_LAYOUT,DEFAULT_LAYOUT_ID));
  updateSettingsKeyState(prefs);
  prefs.registerOnSharedPreferenceChangeListener(this);
  mKeyboards=new HashMap<KeyboardId,SoftReference<LatinKeyboard>>();
  mSymbolsId=makeSymbolsId(false);
  mSymbolsShiftedId=makeSymbolsShiftedId(false);
}
 

Example 60

From project git4idea, under directory /src/git4idea/i18n/.

Source file: GitBundle.java

  15 
vote

private static ResourceBundle getBundle(){
  ResourceBundle bundle=null;
  if (ourBundle != null)   bundle=ourBundle.get();
  if (bundle == null) {
    bundle=ResourceBundle.getBundle(BUNDLE);
    ourBundle=new SoftReference<ResourceBundle>(bundle);
  }
  return bundle;
}
 

Example 61

From project Grammar-Kit, under directory /support/org/intellij/grammar/.

Source file: GrammarMessages.java

  15 
vote

private static ResourceBundle getBundle(){
  ResourceBundle bundle=null;
  if (ourBundle != null)   bundle=ourBundle.get();
  if (bundle == null) {
    bundle=ResourceBundle.getBundle(BUNDLE);
    ourBundle=new SoftReference<ResourceBundle>(bundle);
  }
  return bundle;
}
 

Example 62

From project GreenDroid, under directory /GreenDroid/src/greendroid/image/.

Source file: ImageCache.java

  15 
vote

public Bitmap get(String url){
  final SoftReference<Bitmap> ref=mSoftCache.get(url);
  if (ref == null) {
    return null;
  }
  final Bitmap bitmap=ref.get();
  if (bitmap == null) {
    mSoftCache.remove(url);
  }
  return bitmap;
}
 

Example 63

From project GreenDroidQABar, under directory /src/greendroid/image/.

Source file: ImageCache.java

  15 
vote

public Bitmap get(String url){
  final SoftReference<Bitmap> ref=mSoftCache.get(url);
  if (ref == null) {
    return null;
  }
  final Bitmap bitmap=ref.get();
  if (bitmap == null) {
    mSoftCache.remove(url);
  }
  return bitmap;
}
 

Example 64

From project griffon, under directory /subprojects/griffon-rt/src/main/groovy/griffon/util/.

Source file: Metadata.java

  15 
vote

/** 
 * @return Returns the metadata for the current application
 */
public static Metadata getCurrent(){
  Metadata m=metadata.get();
  if (m == null) {
    metadata=new SoftReference<Metadata>(new Metadata());
    m=metadata.get();
  }
  if (!m.initialized) {
    InputStream input=null;
    try {
      input=fetchApplicationProperties(Thread.currentThread().getContextClassLoader());
      if (input == null)       input=fetchApplicationProperties(Metadata.class.getClassLoader());
      if (input != null) {
        m.load(input);
      }
    }
 catch (    Exception e) {
      throw new RuntimeException("Cannot load application metadata:" + e.getMessage(),e);
    }
 finally {
      closeQuietly(input);
      m.initialized=true;
    }
  }
  return m;
}
 

Example 65

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/cache/lazy/.

Source file: SharedLazyDatabaseMetaDataCache.java

  15 
vote

/** 
 * {@inheritDoc}
 * @see net.sf.hajdbc.cache.DatabaseMetaDataCache#getDatabaseProperties(net.sf.hajdbc.Database,java.sql.Connection)
 */
@Override public DatabaseProperties getDatabaseProperties(D database,Connection connection) throws SQLException {
  Map.Entry<DatabaseProperties,LazyDatabaseMetaDataProvider> entry=this.entryRef.get();
  if (entry == null) {
    DatabaseMetaData metaData=connection.getMetaData();
    Dialect dialect=this.cluster.getDialect();
    DatabaseMetaDataSupport support=this.factory.createSupport(metaData,dialect);
    LazyDatabaseMetaDataProvider provider=new LazyDatabaseMetaDataProvider(metaData);
    DatabaseProperties properties=new LazyDatabaseProperties(provider,support,dialect);
    entry=new AbstractMap.SimpleImmutableEntry<DatabaseProperties,LazyDatabaseMetaDataProvider>(properties,provider);
    this.entryRef=new SoftReference<Map.Entry<DatabaseProperties,LazyDatabaseMetaDataProvider>>(entry);
  }
 else {
    entry.getValue().setConnection(connection);
  }
  return entry.getKey();
}
 

Example 66

From project HeLauncher, under directory /src/com/handlerexploit/launcher_reloaded/.

Source file: LiveFolderAdapter.java

  15 
vote

private Drawable loadIcon(Context context,Cursor cursor,ViewHolder holder){
  Drawable icon=null;
  byte[] data=null;
  if (holder.iconBitmapIndex != -1) {
    data=cursor.getBlob(holder.iconBitmapIndex);
  }
  if (data != null) {
    final SoftReference<Drawable> reference=mCustomIcons.get(holder.id);
    if (reference != null) {
      icon=reference.get();
    }
    if (icon == null) {
      final Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length);
      icon=new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap,context));
      mCustomIcons.put(holder.id,new SoftReference<Drawable>(icon));
    }
  }
 else   if (holder.iconResourceIndex != -1 && holder.iconPackageIndex != -1) {
    final String resource=cursor.getString(holder.iconResourceIndex);
    icon=mIcons.get(resource);
    if (icon == null) {
      try {
        final PackageManager packageManager=context.getPackageManager();
        Resources resources=packageManager.getResourcesForApplication(cursor.getString(holder.iconPackageIndex));
        final int id=resources.getIdentifier(resource,null,null);
        icon=Utilities.createIconThumbnail(resources.getDrawable(id),context);
        mIcons.put(resource,icon);
      }
 catch (      Exception e) {
      }
    }
  }
  return icon;
}
 

Example 67

From project heritrix3, under directory /commons/src/main/java/org/archive/util/.

Source file: ObjectIdentityBdbCache.java

  15 
vote

/** 
 * Call this method when you have an instance when you used the default constructor or when you have a deserialized instance that you want to reconnect with an extant bdbje environment.  Do not call this method if you used the {@link #CachedBdbMap(File,String,Class,Class)} constructor.
 * @param env
 * @param keyClass
 * @param valueClass
 * @param classCatalog
 * @throws DatabaseException
 */
public void initialize(final Environment env,String dbName,final Class valueClass,final StoredClassCatalog classCatalog) throws DatabaseException {
  this.memMap=new ConcurrentHashMap<String,SoftEntry<V>>(8192,0.9f,64);
  this.refQueue=new ReferenceQueue<V>();
  canary=new SoftReference<LowMemoryCanary>(new LowMemoryCanary());
  this.db=openDatabase(env,dbName);
  this.diskMap=createDiskMap(this.db,classCatalog,valueClass);
  this.count=new AtomicLong(diskMap.size());
}
 

Example 68

From project hibernate-validator, under directory /engine/src/main/java/org/hibernate/validator/internal/util/scriptengine/.

Source file: ScriptEvaluatorFactory.java

  15 
vote

/** 
 * Retrieves an instance of this factory.
 * @return A script evaluator factory. Never null.
 */
public static synchronized ScriptEvaluatorFactory getInstance(){
  ScriptEvaluatorFactory theValue=INSTANCE.get();
  if (theValue == null) {
    theValue=new ScriptEvaluatorFactory();
    INSTANCE=new SoftReference<ScriptEvaluatorFactory>(theValue);
  }
  return theValue;
}
 

Example 69

From project httpClient, under directory /httpclient/src/main/java/org/apache/http/impl/cookie/.

Source file: DateUtils.java

  15 
vote

/** 
 * creates a  {@link SimpleDateFormat} for the requested format string.
 * @param pattern a non-<code>null</code> format String according to {@link SimpleDateFormat}. The format is not checked against <code>null</code> since all paths go through {@link DateUtils}.
 * @return the requested format. This simple dateformat should not be usedto  {@link SimpleDateFormat#applyPattern(String) apply} to adifferent pattern.
 */
public static SimpleDateFormat formatFor(String pattern){
  SoftReference<Map<String,SimpleDateFormat>> ref=THREADLOCAL_FORMATS.get();
  Map<String,SimpleDateFormat> formats=ref.get();
  if (formats == null) {
    formats=new HashMap<String,SimpleDateFormat>();
    THREADLOCAL_FORMATS.set(new SoftReference<Map<String,SimpleDateFormat>>(formats));
  }
  SimpleDateFormat format=formats.get(pattern);
  if (format == null) {
    format=new SimpleDateFormat(pattern,Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    formats.put(pattern,format);
  }
  return format;
}
 

Example 70

From project ICS_LatinIME_QHD, under directory /java/src/com/android/inputmethod/keyboard/.

Source file: KeyboardSwitcher.java

  15 
vote

private LatinKeyboard getKeyboard(KeyboardId id){
  final SoftReference<LatinKeyboard> ref=mKeyboardCache.get(id);
  LatinKeyboard keyboard=(ref == null) ? null : ref.get();
  if (keyboard == null) {
    final Locale savedLocale=LocaleUtils.setSystemLocale(mResources,id.mLocale);
    try {
      final LatinKeyboard.Builder builder=new LatinKeyboard.Builder(mThemeContext);
      builder.load(id);
      builder.setTouchPositionCorrectionEnabled(mSubtypeSwitcher.currentSubtypeContainsExtraValueKey(LatinIME.SUBTYPE_EXTRA_VALUE_SUPPORT_TOUCH_POSITION_CORRECTION));
      keyboard=builder.build();
    }
  finally {
      LocaleUtils.setSystemLocale(mResources,savedLocale);
    }
    mKeyboardCache.put(id,new SoftReference<LatinKeyboard>(keyboard));
    if (DEBUG_CACHE) {
      Log.d(TAG,"keyboard cache size=" + mKeyboardCache.size() + ": "+ ((ref == null) ? "LOAD" : "GCed")+ " id="+ id+ " theme="+ Keyboard.themeName(keyboard.mThemeId));
    }
  }
 else   if (DEBUG_CACHE) {
    Log.d(TAG,"keyboard cache size=" + mKeyboardCache.size() + ": HIT  id="+ id+ " theme="+ Keyboard.themeName(keyboard.mThemeId));
  }
  keyboard.onAutoCorrectionStateChanged(mIsAutoCorrectionActive);
  keyboard.setShiftLocked(false);
  keyboard.setShifted(false);
  keyboard.setSpacebarTextFadeFactor(0.0f,null);
  keyboard.updateShortcutKey(mSubtypeSwitcher.isShortcutImeReady(),null);
  return keyboard;
}
 

Example 71

From project ImageLoader, under directory /core/src/main/java/com/novoda/imageloader/core/cache/.

Source file: SoftMapCache.java

  15 
vote

@Override public Bitmap get(String url,int width,int height){
  SoftReference<Bitmap> bmpr=cache.get(url);
  if (bmpr == null) {
    return null;
  }
  return bmpr.get();
}
 

Example 72

From project indextank-engine, under directory /cojen-2.2.1-sources/org/cojen/classfile/.

Source file: TypeDesc.java

  15 
vote

public final synchronized Class toClass(){
  Class clazz;
  if (mClassRef != null) {
    clazz=mClassRef.get();
    if (clazz != null) {
      return clazz;
    }
  }
  clazz=toClass(null);
  mClassRef=new SoftReference<Class>(clazz);
  return clazz;
}
 

Example 73

From project jackrabbit-oak, under directory /oak-core/src/main/java/org/apache/jackrabbit/mk/simple/.

Source file: StringCache.java

  15 
vote

private static String[] getCache(){
  String[] cache;
  if (softCache != null) {
    cache=softCache.get();
    if (cache != null) {
      return cache;
    }
  }
  try {
    cache=new String[OBJECT_CACHE_SIZE];
  }
 catch (  OutOfMemoryError e) {
    return null;
  }
  softCache=new SoftReference<String[]>(cache);
  return cache;
}
 

Example 74

From project jaffl, under directory /src/com/kenai/jaffl/provider/.

Source file: StringIO.java

  15 
vote

private static CharsetEncoder getEncoder(Charset charset){
  SoftReference<CharsetEncoder> ref=StaticDataHolder.ENCODER.get();
  CharsetEncoder encoder;
  if (ref != null && (encoder=ref.get()) != null && encoder.charset() == charset) {
    return encoder;
  }
  return initEncoder(charset);
}
 

Example 75

From project jangod, under directory /core/net/asfun/jangod/cache/.

Source file: ConcurrentHashPool.java

  15 
vote

@Override public T pop(){
  Iterator<Integer> keys=pool.keySet().iterator();
  while (keys.hasNext()) {
    Reference<T> ref=pool.remove(keys.next());
    if (ref != null) {
      if (ref instanceof SoftReference<?>) {
        counter.decrementAndGet();
      }
      return ref.get();
    }
  }
  return null;
}
 

Example 76

From project jCAE, under directory /viewer3d-amibe/src/org/jcae/viewer3d/.

Source file: OEMMBehavior.java

  15 
vote

public OEMMBehavior(View canvas,OEMM oemm,OEMM coarseOEMM){
  visibleMeshBranchGroup.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
  visibleMeshBranchGroup.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
  cacheOemmNodeId2BranchGroup=new SoftReference[oemm.getNumberOfLeaves()];
  canvas.add(new ViewableBG(visibleMeshBranchGroup));
  boolean cloneBoundaryTriangles=Boolean.getBoolean("org.jcae.viewer3d.OEMMBehavior.cloneBoundaryTriangles");
  fineReader=new MeshReader(oemm);
  fineReader.setLoadNonReadableTriangles(true);
  mtb.addTriangleList();
  coarseReader=new MeshReader(coarseOEMM);
  coarseReader.setLoadNonReadableTriangles(cloneBoundaryTriangles);
  coarseReader.buildMeshes(mtb);
  for (int i=0, n=coarseOEMM.getNumberOfLeaves(); i < n; i++) {
    Integer II=Integer.valueOf(i);
    Mesh mesh=coarseReader.getMesh(i);
    ViewHolder vh=new ViewHolder(i,mesh);
    vh.setViewElem(OEMMViewer.meshOEMM(mesh));
    coarseOemmNodeId2BranchGroup.put(II,vh);
    addViewHolderToBranchGroup(II,coarseOemmNodeId2BranchGroup);
  }
  setSchedulingBounds(new BoundingSphere(new Point3d(),Double.MAX_VALUE));
  double[] coords=oemm.getCoords(true);
  computeVoxels(canvas,coords);
  this.oemm=oemm;
  d2limit=2 * (coords[0] - coords[6 * 4 * 3 - 6]);
  wakeupFrame=new WakeupOnElapsedFrames(1);
  wakeupTransf=new WakeupOnTransformChange(view.getViewingPlatform().getViewPlatformTransform());
  maxNumberOfTriangles=Long.getLong("org.jcae.viewer3d.OEMMBehavior.maxNumberOfTriangles",DEFAULT_MAX_TRIANGLES_NBR).longValue();
  if (logger.isLoggable(Level.INFO)) {
    logger.info("Maximal number of triangles: " + maxNumberOfTriangles);
  }
}
 

Example 77

From project JGit, under directory /org.spearce.jgit/src/org/spearce/jgit/lib/.

Source file: UnpackedObjectCache.java

  15 
vote

static synchronized void store(final WindowedFile pack,final long position,final byte[] data,final int objectType){
  if (data.length > maxByteCount)   return;
  final Slot e=cache[hash(position)];
  clearEntry(e);
  openByteCount+=data.length;
  releaseMemory();
  e.provider=pack;
  e.position=position;
  e.sz=data.length;
  e.data=new SoftReference<Entry>(new Entry(data,objectType));
  moveToHead(e);
}
 

Example 78

From project jhilbert, under directory /src/main/java/jhilbert/utils/.

Source file: AutoCache.java

  15 
vote

/** 
 * Clean up collected entries.
 */
private void cleanup(){
  final Iterator<Map.Entry<K,SoftReference<V>>> i=backingMap.entrySet().iterator();
  while (i.hasNext()) {
    if (i.next().getValue().get() == null)     i.remove();
  }
}
 

Example 79

From project jSCSI, under directory /bundles/commons/src/main/java/org/jscsi/utils/.

Source file: SoftHashMap.java

  15 
vote

/** 
 * Constructor that allows to specify how many strong references should be used internally.
 * @param initStrongReferenceCount Number of internal strong references.
 */
@SuppressWarnings("unchecked") public SoftHashMap(final int initStrongReferenceCount){
  internalMap=new HashMap<K,SoftReference<V>>();
  strongReferenceCount=initStrongReferenceCount;
  strongReferenceArray=(V[])new Object[initStrongReferenceCount];
  currentStrongReferenceOffset=0;
  queue=new ReferenceQueue<SoftValue<V>>();
}
 

Example 80

From project JsTestDriver, under directory /idea-plugin/src/com/google/jstestdriver/idea/.

Source file: MessageBundle.java

  15 
vote

public static ResourceBundle getBundle(){
  ResourceBundle bundle=null;
  if (MessageBundle.bundle != null) {
    bundle=MessageBundle.bundle.get();
  }
  if (bundle == null) {
    bundle=ResourceBundle.getBundle(MessageBundle.BUNDLE);
    MessageBundle.bundle=new SoftReference<ResourceBundle>(bundle);
  }
  return bundle;
}
 

Example 81

From project la-clojure, under directory /src/org/jetbrains/plugins/clojure/.

Source file: ClojureBundle.java

  15 
vote

private static ResourceBundle getBundle(){
  ResourceBundle bundle=null;
  if (ourBundle != null)   bundle=ourBundle.get();
  if (bundle == null) {
    bundle=ResourceBundle.getBundle(BUNDLE);
    ourBundle=new SoftReference<ResourceBundle>(bundle);
  }
  return bundle;
}
 

Example 82

From project LateralGM, under directory /org/lateralgm/components/.

Source file: ActionList.java

  15 
vote

public Component getListCellRendererComponent(JList list,Object cell,int index,boolean isSelected,boolean hasFocus){
  final Action cellAction=(Action)cell;
  SoftReference<ActionRendererComponent> arcref=lcrMap.get(cellAction);
  ActionRendererComponent arc=null;
  if (arcref != null)   arc=arcref.get();
  if (arc == null) {
    arc=new ActionRendererComponent(cellAction,list);
    lcrMap.put(cellAction,new SoftReference<ActionRendererComponent>(arc));
  }
  ListModel lm=list.getModel();
  try {
    if (lm instanceof ActionListModel)     arc.setIndent(((ActionListModel)lm).indents.get(index));
  }
 catch (  IndexOutOfBoundsException e) {
  }
  arc.setSelected(isSelected);
  return arc;
}
 

Example 83

From project liquidroid, under directory /src/liqui/droid/util/.

Source file: GravatarImage.java

  15 
vote

@Override protected boolean removeEldestEntry(LinkedHashMap.Entry<String,Bitmap> eldest){
  if (size() > HARD_CACHE_CAPACITY) {
    sSoftBitmapCache.put(eldest.getKey(),new SoftReference<Bitmap>(eldest.getValue()));
    return true;
  }
 else   return false;
}
 

Example 84

From project maven-scm, under directory /maven-scm-api/src/main/java/org/apache/maven/scm/util/.

Source file: ThreadSafeDateFormat.java

  15 
vote

public SoftReference<SimpleDateFormat> get(){
  SoftReference<SimpleDateFormat> softRef=super.get();
  if (softRef == null || softRef.get() == null) {
    softRef=new SoftReference<SimpleDateFormat>(new SimpleDateFormat(m_sDateFormat));
    super.set(softRef);
  }
  return softRef;
}
 

Example 85

From project mediautilities, under directory /src/ac/robinson/util/.

Source file: ImageCacheUtilities.java

  15 
vote

/** 
 * Retrieves a drawable from the cache, identified by the specified id. If the drawable does not exist in the cache, it is loaded and added to the cache. If the drawable cannot be added to the cache, the specified default drwaable is returned.
 * @param id The id of the drawable to retrieve
 * @param defaultIcon The default drawable returned if no drawable can be found that matches the id
 * @return The drawable identified by id or defaultIcon
 */
public static FastBitmapDrawable getCachedIcon(File cacheDirectory,String id,FastBitmapDrawable defaultIcon){
  FastBitmapDrawable drawable=null;
  SoftReference<FastBitmapDrawable> reference=sArtCache.get(id);
  if (reference != null) {
    drawable=reference.get();
  }
  if (drawable == null) {
    final Bitmap bitmap=loadIcon(cacheDirectory,id);
    if (bitmap != null) {
      drawable=new FastBitmapDrawable(bitmap);
    }
 else {
      drawable=NULL_DRAWABLE;
    }
    sArtCache.put(id,new SoftReference<FastBitmapDrawable>(drawable));
  }
  return drawable == NULL_DRAWABLE ? defaultIcon : drawable;
}
 

Example 86

From project MIT-Mobile-for-Android, under directory /src/edu/mit/mitmobile2/maps/.

Source file: MapTilesManager.java

  15 
vote

public Bitmap getBitmap(int col,int row,int zoom,boolean keepStrongReference){
  String bitmapKey=imagesHashKey(col,row,zoom);
  Bitmap bitmap=imagesMapStrongRefs.get(bitmapKey);
  if (bitmap != null) {
    imagesMapStrongRefs.remove(bitmapKey);
    imagesMapStrongRefs.put(bitmapKey,bitmap);
    return bitmap;
  }
  SoftReference<Bitmap> bitmapRef=imagesMap.get(bitmapKey);
  if (bitmapRef != null) {
    bitmap=bitmapRef.get();
    if (bitmap != null && keepStrongReference) {
      imagesMapStrongRefs.put(bitmapKey,bitmap);
    }
    return bitmap;
  }
 else {
    return null;
  }
}
 

Example 87

From project MyHeath-Android, under directory /src/com/buaa/shortytall/network/.

Source file: ImageCache.java

  15 
vote

@Override public void run(){
  if (!TextUtils.isEmpty(mUrl) && mBitmap != null) {
    memCache.put(mUrl,new SoftReference<Bitmap>(mBitmap));
    if (freshImgWaiting) {
      return;
    }
    freshImgWaiting=true;
    handler.postDelayed(new Runnable(){
      @Override public void run(){
        handler.sendEmptyMessage(MyHealth.Msg.IMG_LOADED_COMPLETED);
        freshImgWaiting=false;
      }
    }
,100);
  }
}
 

Example 88

From project nenya, under directory /core/src/main/java/com/threerings/media/tile/.

Source file: TileManager.java

  15 
vote

/** 
 * Used to load and cache tilesets loaded via  {@link #loadTileSet}.
 */
protected UniformTileSet loadCachedTileSet(String bundle,String imgPath,int width,int height){
  String key=bundle + "::" + imgPath;
  SoftReference<UniformTileSet> ref=_handcache.get(key);
  UniformTileSet uts=(ref == null) ? null : ref.get();
  if (uts == null) {
    uts=new UniformTileSet();
    uts.setImageProvider(_defaultProvider);
    uts.setImagePath(imgPath);
    uts.setWidth(width);
    uts.setHeight(height);
    _handcache.put(key,new SoftReference<UniformTileSet>(uts));
  }
  return uts;
}
 

Example 89

From project OpenTripPlanner, under directory /opentripplanner-utils/src/main/java/org/opentripplanner/common/geometry/.

Source file: PackedCoordinateSequence.java

  15 
vote

/** 
 * @see com.vividsolutions.jts.geom.CoordinateSequence#toCoordinateArray()
 */
public Coordinate[] toCoordinateArray(){
  Coordinate[] coords=getCachedCoords();
  if (coords != null)   return coords;
  coords=new Coordinate[size()];
  for (int i=0; i < coords.length; i++) {
    coords[i]=getCoordinateInternal(i);
  }
  coordRef=new SoftReference<Coordinate[]>(coords);
  return coords;
}
 

Example 90

From project Orebfuscator, under directory /src/com/lishid/orebfuscator/cache/.

Source file: ObfuscatedDataCache.java

  15 
vote

public static synchronized RegionFile getRegionFile(File folder,int x,int z){
  File path=new File(folder,"region");
  File file=new File(path,"r." + (x >> 5) + "."+ (z >> 5)+ ".mcr");
  Reference<RegionFile> reference=cachedRegionFiles.get(file);
  if (reference != null) {
    RegionFile regionFile=(RegionFile)reference.get();
    if (regionFile != null) {
      return regionFile;
    }
  }
  if (!path.exists()) {
    path.mkdirs();
  }
  if (cachedRegionFiles.size() >= OrebfuscatorConfig.getMaxLoadedCacheFiles()) {
    clearCache();
  }
  RegionFile regionFile=new RegionFile(file);
  cachedRegionFiles.put(file,new SoftReference<RegionFile>(regionFile));
  return regionFile;
}
 

Example 91

From project org.ops4j.pax.runner, under directory /pax-runner-idea/ui/src/main/java/org/ops4j/pax/idea/runner/.

Source file: OsgiResourceBundle.java

  15 
vote

private static ResourceBundle getBundle(){
  ResourceBundle bundle=null;
  if (ourBundle != null) {
    bundle=ourBundle.get();
  }
  if (bundle == null) {
    bundle=ResourceBundle.getBundle(BUNDLE);
    ourBundle=new SoftReference<ResourceBundle>(bundle);
  }
  return bundle;
}
 

Example 92

From project orientdb, under directory /core/src/main/java/com/orientechnologies/orient/core/db/graph/.

Source file: OGraphEdge.java

  15 
vote

public OGraphEdge(final ODatabaseGraphTx iDatabase,final String iClassName,final OGraphVertex iOutNode,final OGraphVertex iInNode){
  this(iDatabase,iClassName);
  in=new SoftReference<OGraphVertex>(iInNode);
  out=new SoftReference<OGraphVertex>(iOutNode);
  set(IN,iInNode.getDocument());
  set(OUT,iOutNode.getDocument());
}
 

Example 93

From project packages_apps_ROMControl, under directory /src/com/koushikdutta/urlimageviewhelper/.

Source file: SoftReferenceHashTable.java

  15 
vote

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;
}
 

Example 94

From project pandoroid, under directory /src/com/aregner/android/pandoid/.

Source file: ImageDownloader.java

  15 
vote

@Override protected boolean removeEldestEntry(LinkedHashMap.Entry<String,Bitmap> eldest){
  if (size() > HARD_CACHE_CAPACITY) {
    sSoftBitmapCache.put(eldest.getKey(),new SoftReference<Bitmap>(eldest.getValue()));
    return true;
  }
 else   return false;
}
 

Example 95

From project persistence, under directory /src/main/java/com/codeslap/persistence/suggestions/.

Source file: SuggestionsProvider.java

  15 
vote

@Override public Cursor query(Uri uri,String[] projection,String where,String[] whereArgs,String sortOrder){
  List<T> findAll=new ArrayList<T>();
  String query=uri.getLastPathSegment();
  if (!SearchManager.SUGGEST_URI_PATH_QUERY.equals(query) && !TextUtils.isEmpty(query)) {
    List<T> ts=queryItems(query);
    findAll.addAll(ts);
  }
  List<SuggestionInfo> suggestionInfos=new ArrayList<SuggestionInfo>();
  for (  T object : findAll) {
    SoftReference<SuggestionInfo> soft;
    if (suggestions.containsKey(object) && suggestions.get(object).get() != null) {
      soft=suggestions.get(object);
    }
 else {
      soft=new SoftReference<SuggestionInfo>(buildSuggestionInfo(object));
      suggestions.put(object,soft);
    }
    suggestionInfos.add(soft.get());
  }
  return new SuggestionsCursor(suggestionInfos);
}
 

Example 96

From project platform_external_apache-http, under directory /src/org/apache/http/impl/cookie/.

Source file: DateUtils.java

  15 
vote

/** 
 * creates a  {@link SimpleDateFormat} for the requested format string.
 * @param pattern a non-<code>null</code> format String according to {@link SimpleDateFormat}. The format is not checked against <code>null</code> since all paths go through {@link DateUtils}.
 * @return the requested format. This simple dateformat should not be usedto  {@link SimpleDateFormat#applyPattern(String) apply} to adifferent pattern.
 */
public static SimpleDateFormat formatFor(String pattern){
  SoftReference<Map<String,SimpleDateFormat>> ref=THREADLOCAL_FORMATS.get();
  Map<String,SimpleDateFormat> formats=ref.get();
  if (formats == null) {
    formats=new HashMap<String,SimpleDateFormat>();
    THREADLOCAL_FORMATS.set(new SoftReference<Map<String,SimpleDateFormat>>(formats));
  }
  SimpleDateFormat format=formats.get(pattern);
  if (format == null) {
    format=new SimpleDateFormat(pattern,Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    formats.put(pattern,format);
  }
  return format;
}
 

Example 97

From project platform_packages_apps_contacts, under directory /src/com/android/contacts/.

Source file: ContactPhotoManager.java

  15 
vote

/** 
 * 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 inthe holder, it will not be necessary to decode the bitmap.
 */
private static void inflateBitmap(BitmapHolder holder,int requestedExtent){
  final int sampleSize=BitmapUtil.findOptimalSampleSize(holder.originalSmallerExtent,requestedExtent);
  byte[] bytes=holder.bytes;
  if (bytes == null || bytes.length == 0) {
    return;
  }
  if (sampleSize == holder.decodedSampleSize) {
    if (holder.bitmapRef != null) {
      holder.bitmap=holder.bitmapRef.get();
      if (holder.bitmap != null) {
        return;
      }
    }
  }
  try {
    Bitmap bitmap=BitmapUtil.decodeBitmapFromBytes(bytes,sampleSize);
    if (DEBUG_SIZES) {
      Bitmap original=bitmap;
      bitmap=bitmap.copy(bitmap.getConfig(),true);
      original.recycle();
      Canvas canvas=new Canvas(bitmap);
      Paint paint=new Paint();
      paint.setTextSize(16);
      paint.setColor(Color.BLUE);
      paint.setStyle(Style.FILL);
      canvas.drawRect(0.0f,0.0f,50.0f,20.0f,paint);
      paint.setColor(Color.WHITE);
      paint.setAntiAlias(true);
      canvas.drawText(bitmap.getWidth() + "/" + sampleSize,0,15,paint);
    }
    holder.decodedSampleSize=sampleSize;
    holder.bitmap=bitmap;
    holder.bitmapRef=new SoftReference<Bitmap>(bitmap);
    if (DEBUG) {
      Log.d(TAG,"inflateBitmap " + btk(bytes.length) + " -> "+ bitmap.getWidth()+ "x"+ bitmap.getHeight()+ ", "+ btk(bitmap.getByteCount()));
    }
  }
 catch (  OutOfMemoryError e) {
  }
}
 

Example 98

From project platform_packages_apps_Gallery2_1, under directory /src/com/android/gallery3d/data/.

Source file: LocalMergeAlbum.java

  15 
vote

public MediaItem getItem(int index){
  boolean needLoading=false;
  ArrayList<MediaItem> cache=null;
  if (mCacheRef == null || index < mStartPos || index >= mStartPos + PAGE_SIZE) {
    needLoading=true;
  }
 else {
    cache=mCacheRef.get();
    if (cache == null) {
      needLoading=true;
    }
  }
  if (needLoading) {
    cache=mBaseSet.getMediaItem(index,PAGE_SIZE);
    mCacheRef=new SoftReference<ArrayList<MediaItem>>(cache);
    mStartPos=index;
  }
  if (index < mStartPos || index >= mStartPos + cache.size()) {
    return null;
  }
  return cache.get(index - mStartPos);
}
 

Example 99

From project platform_packages_apps_launcher, under directory /src/com/android/launcher/.

Source file: LiveFolderAdapter.java

  15 
vote

private Drawable loadIcon(Context context,Cursor cursor,ViewHolder holder){
  Drawable icon=null;
  byte[] data=null;
  if (holder.iconBitmapIndex != -1) {
    data=cursor.getBlob(holder.iconBitmapIndex);
  }
  if (data != null) {
    final SoftReference<Drawable> reference=mCustomIcons.get(holder.id);
    if (reference != null) {
      icon=reference.get();
    }
    if (icon == null) {
      final Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length);
      icon=new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap,mContext));
      mCustomIcons.put(holder.id,new SoftReference<Drawable>(icon));
    }
  }
 else   if (holder.iconResourceIndex != -1 && holder.iconPackageIndex != -1) {
    final String resource=cursor.getString(holder.iconResourceIndex);
    icon=mIcons.get(resource);
    if (icon == null) {
      try {
        final PackageManager packageManager=context.getPackageManager();
        Resources resources=packageManager.getResourcesForApplication(cursor.getString(holder.iconPackageIndex));
        final int id=resources.getIdentifier(resource,null,null);
        icon=Utilities.createIconThumbnail(resources.getDrawable(id),mContext);
        mIcons.put(resource,icon);
      }
 catch (      Exception e) {
      }
    }
  }
  return icon;
}
 

Example 100

From project platform_packages_apps_mms, under directory /src/com/android/mms/model/.

Source file: ImageModel.java

  15 
vote

public Bitmap getBitmap(int width,int height){
  Bitmap bm=mFullSizeBitmapCache.get();
  if (bm == null) {
    try {
      bm=createBitmap(Math.max(width,height),getUri());
      if (bm != null) {
        mFullSizeBitmapCache=new SoftReference<Bitmap>(bm);
      }
    }
 catch (    OutOfMemoryError ex) {
    }
  }
  return bm;
}
 

Example 101

From project platform_packages_providers_contactsprovider, under directory /src/com/android/providers/contacts/aggregation/util/.

Source file: CommonNicknameCache.java

  15 
vote

/** 
 * Returns nickname cluster IDs or null. Maintains cache.
 */
public 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;
}
 

Example 102

From project pomodoro-tm, under directory /src/ru/greeneyes/project/pomidoro/.

Source file: UIBundle.java

  15 
vote

private static ResourceBundle getBundle(){
  ResourceBundle bundle=null;
  if (ourBundle != null)   bundle=ourBundle.get();
  if (bundle == null) {
    bundle=ResourceBundle.getBundle(PATH_TO_BUNDLE);
    ourBundle=new SoftReference<ResourceBundle>(bundle);
  }
  return bundle;
}
 

Example 103

From project portal, under directory /portal-core/src/main/java/org/devproof/portal/core/module/common/panel/captcha/.

Source file: KittenCaptchaPanel.java

  15 
vote

/** 
 * @return Rendered image data
 */
@Override protected byte[] getImageData(){
  setLastModifiedTime(Time.now());
  final WebResponse response=(WebResponse)RequestCycle.get().getResponse();
  response.setHeader("Cache-Control","no-cache, must-revalidate, max-age=0, no-store");
  if (data == null || data.get() == null) {
    final BufferedImage composedImage=animals.createImage();
    data=new SoftReference<byte[]>(toImageData(composedImage));
  }
  return data.get();
}
 

Example 104

From project preon, under directory /preon-binding/src/main/java/org/codehaus/preon/util/.

Source file: LazyLoadingReference.java

  15 
vote

/** 
 * Returns an instance of  {@link T}, lazily constructed on demand using the  {@link #loader Loader}.
 * @return The referenced instance of {@link T}.
 * @throws InterruptedException When blocking call is interrupted.
 * @throws ExcecutionException  When the {@link Loader} threw an exception trying to load the data.
 */
public T get() throws InterruptedException, ExecutionException {
  while (true) {
    SoftReference<Future<T>> softReference=reference.get();
    boolean validSoftReference=true;
    if (softReference == null) {
      Callable<T> eval=new Callable<T>(){
        public T call() throws Exception {
          return loader.load();
        }
      }
;
      FutureTask<T> task=new FutureTask<T>(eval);
      softReference=new SoftReference<Future<T>>(task);
      if (validSoftReference=reference.compareAndSet(null,softReference)) {
        task.run();
      }
    }
    if (validSoftReference) {
      try {
        Future<T> future=softReference.get();
        if (future != null) {
          return future.get();
        }
 else {
          reference.compareAndSet(softReference,null);
        }
      }
 catch (      CancellationException e) {
        reference.compareAndSet(softReference,null);
      }
    }
  }
}
 

Example 105

From project RA_Launcher, under directory /src/com/android/ra/launcher/.

Source file: LiveFolderAdapter.java

  15 
vote

private Drawable loadIcon(Context context,Cursor cursor,ViewHolder holder){
  Drawable icon=null;
  byte[] data=null;
  if (holder.iconBitmapIndex != -1) {
    data=cursor.getBlob(holder.iconBitmapIndex);
  }
  if (data != null) {
    final SoftReference<Drawable> reference=mCustomIcons.get(holder.id);
    if (reference != null) {
      icon=reference.get();
    }
    if (icon == null) {
      final Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length);
      final Bitmap resampled=Utilities.resampleIconBitmap(bitmap,mLauncher);
      if (bitmap != resampled) {
        bitmap.recycle();
      }
      icon=new FastBitmapDrawable(resampled);
      mCustomIcons.put(holder.id,new SoftReference<Drawable>(icon));
    }
  }
 else   if (holder.iconResourceIndex != -1 && holder.iconPackageIndex != -1) {
    final String resource=cursor.getString(holder.iconResourceIndex);
    icon=mIcons.get(resource);
    if (icon == null) {
      try {
        final PackageManager packageManager=context.getPackageManager();
        Resources resources=packageManager.getResourcesForApplication(cursor.getString(holder.iconPackageIndex));
        final int id=resources.getIdentifier(resource,null,null);
        icon=new FastBitmapDrawable(Utilities.createIconBitmap(resources.getDrawable(id),mLauncher));
        mIcons.put(resource,icon);
      }
 catch (      Exception e) {
      }
    }
  }
  return icon;
}
 

Example 106

From project RebeLauncher, under directory /src/com/dirtypepper/rebelauncher/.

Source file: LiveFolderAdapter.java

  15 
vote

private Drawable loadIcon(Context context,Cursor cursor,ViewHolder holder){
  Drawable icon=null;
  byte[] data=null;
  if (holder.iconBitmapIndex != -1) {
    data=cursor.getBlob(holder.iconBitmapIndex);
  }
  if (data != null) {
    final SoftReference<Drawable> reference=mCustomIcons.get(holder.id);
    if (reference != null) {
      icon=reference.get();
    }
    if (icon == null) {
      final Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length);
      icon=new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap,mLauncher));
      mCustomIcons.put(holder.id,new SoftReference<Drawable>(icon));
    }
  }
 else   if (holder.iconResourceIndex != -1 && holder.iconPackageIndex != -1) {
    final String resource=cursor.getString(holder.iconResourceIndex);
    icon=mIcons.get(resource);
    if (icon == null) {
      try {
        final PackageManager packageManager=context.getPackageManager();
        Resources resources=packageManager.getResourcesForApplication(cursor.getString(holder.iconPackageIndex));
        final int id=resources.getIdentifier(resource,null,null);
        icon=Utilities.createIconThumbnail(resources.getDrawable(id),mLauncher);
        mIcons.put(resource,icon);
      }
 catch (      Exception e) {
      }
    }
  }
  return icon;
}