Java Code Examples for java.lang.ref.WeakReference#get()

The following examples show how to use java.lang.ref.WeakReference#get() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public MemoryBlock allocate(long size) throws OutOfMemoryError {
  if (shouldPool(size)) {
    synchronized (this) {
      final LinkedList<WeakReference<MemoryBlock>> pool = bufferPoolsBySize.get(size);
      if (pool != null) {
        while (!pool.isEmpty()) {
          final WeakReference<MemoryBlock> blockReference = pool.pop();
          final MemoryBlock memory = blockReference.get();
          if (memory != null) {
            assert (memory.size() == size);
            return memory;
          }
        }
        bufferPoolsBySize.remove(size);
      }
    }
  }
  long[] array = new long[(int) ((size + 7) / 8)];
  return new MemoryBlock(array, Platform.LONG_ARRAY_OFFSET, size);
}
 
Example 2
Source Project: Pydev   File: ConsoleColorCache.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void addRef(IOConsole console) {
    synchronized (referencesLock) {
        //We'll clear the current references and add the new one if it's not there already.
        int size = weakrefs.size();
        for (int i = 0; i < size; i++) {
            WeakReference<IOConsole> ref = weakrefs.get(i);
            Object object = ref.get();
            if (object == console) {
                return; //already there (nothing to add).
            }
            if (object == null) {
                weakrefs.remove(i);
                i--;
                size--;
            }
        }
        //Add the new reference.
        weakrefs.add(new WeakReference<IOConsole>(console));
    }
}
 
Example 3
/**
 * Notification that the pythonpath has been rebuilt.
 * 
 * @param project is the project that had the pythonpath rebuilt
 * @param nature the nature related to the project (can be null if the nature has actually been removed)
 */
public static void notifyPythonPathRebuilt(IProject project, IPythonNature nature) {
    for (Iterator<WeakReference<IPythonNatureListener>> it = pythonNatureListeners.iterator(); it.hasNext();) {
        WeakReference<IPythonNatureListener> ref = it.next();
        try {
            IPythonNatureListener listener = ref.get();
            if (listener == null) {
                it.remove();
            } else {
                listener.notifyPythonPathRebuilt(project, nature);
            }
        } catch (Throwable e) {
            Log.log(e);
        }
    }
}
 
Example 4
public void removeLoadingFileObserver(FileDownloadProgressListener observer) {
    if (listenerInProgress) {
        deleteLaterArray.add(observer);
        return;
    }
    String fileName = observersByTag.get(observer.getObserverTag());
    if (fileName != null) {
        ArrayList<WeakReference<FileDownloadProgressListener>> arrayList = loadingFileObservers.get(fileName);
        if (arrayList != null) {
            for (int a = 0; a < arrayList.size(); a++) {
                WeakReference<FileDownloadProgressListener> reference = arrayList.get(a);
                if (reference.get() == null || reference.get() == observer) {
                    arrayList.remove(a);
                    a--;
                }
            }
            if (arrayList.isEmpty()) {
                loadingFileObservers.remove(fileName);
            }
        }
        observersByTag.remove(observer.getObserverTag());
    }
}
 
Example 5
Source Project: android   File: BitmapUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 压缩图片,现根据储存进行等比例压缩,然后根据大小进行质量压缩
 *
 * @param path    图片路径
 * @param maxSize 最大图片大小
 * @param rqsW    要压缩到的宽度
 * @param rqsH    要压缩到的高度
 * @return 压缩后的图片byte数组
 */
public static byte[] compressBitmap(String path, int maxSize, int rqsW, int rqsH) {
    if (TextUtils.isEmpty(path)) return null;
    try {
        // 首先根据图片制定的尺寸大小来压缩
        WeakReference<Bitmap> bitmap = cprsBmpBySize(path, rqsW, rqsH);
        // 进行自动旋转
        WeakReference<Bitmap> rotatedBmp = autoRotateBitmap(path, bitmap);
        if (bitmap != null && rotatedBmp != null && bitmap.get() != rotatedBmp.get()) {
            bitmap.get().recycle();
            bitmap.clear();
        }
        // 然后根据图片的size大小来进行图片的质量压缩
        return cprsBmpByQuality(rotatedBmp, maxSize);
    } catch (Exception o) {
        return null;
    }
}
 
Example 6
@Override
public void onTerminate(boolean restart) {
    mRestartChromeOnDestroy = restart;

    for (WeakReference<Activity> weakActivity : ApplicationStatus.getRunningActivities()) {
        Activity activity = weakActivity.get();
        if (activity != null) {
            ApplicationStatus.registerStateListenerForActivity(this, activity);
            mRemainingActivitiesCount++;
            activity.finish();
        }
    }

    // Start the Activity that will ultimately kill this process.
    fireBrowserRestartActivityIntent(BrowserRestartActivity.ACTION_START_WATCHDOG);
}
 
Example 7
@Override
public BundleFileSystem getFileSystem(URI uri) {
	synchronized (openFilesystems) {
		URI baseURI = baseURIFor(uri);
		WeakReference<BundleFileSystem> ref = openFilesystems.get(baseURI);
		if (ref == null) {
			throw new FileSystemNotFoundException(uri.toString());
		}
		BundleFileSystem fs = ref.get();
		if (fs == null) {
			openFilesystems.remove(baseURI);
			throw new FileSystemNotFoundException(uri.toString());
		}
		return fs;
	}
}
 
Example 8
private void dispatchRestoreInstanceState(Bundle state) {
    SparseArray<Parcelable> presenterStates = state.getSparseParcelableArray(PRESENTER_KEY);

    if (presenterStates == null || mPresenters.isEmpty()) return;

    for (WeakReference<MenuPresenter> ref : mPresenters) {
        final MenuPresenter presenter = ref.get();
        if (presenter == null) {
            mPresenters.remove(ref);
        } else {
            final int id = presenter.getId();
            if (id > 0) {
                Parcelable parcel = presenterStates.get(id);
                if (parcel != null) {
                    presenter.onRestoreInstanceState(parcel);
                }
            }
        }
    }
}
 
Example 9
public T get() {
  WeakReference<T> weakRef = t.get();
  if (weakRef == null) {
    T iv = initialValue();
    if (iv != null) {
      set(iv);
      return iv;
    } else {
      return null;
    }
  } else {
    maybePurge();
    return weakRef.get();
  }
}
 
Example 10
Source Project: kripton   File: DaoPersonImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Invalidate livedata.</p>
 *
 */
public void invalidateLiveData() {
  for (WeakReference<LiveDataHandler> item: liveDatas) {
    if (item.get()!=null) {
      item.get().invalidate();
    }
  }
}
 
Example 11
Source Project: jdk8u_jdk   File: VMState.java    License: GNU General Public License v2.0 5 votes vote down vote up
private synchronized void processVMAction(VMAction action) {
    if (!notifyingListeners) {
        // Prevent recursion
        notifyingListeners = true;

        Iterator<WeakReference<VMListener>> iter = listeners.iterator();
        while (iter.hasNext()) {
            WeakReference<VMListener> ref = iter.next();
            VMListener listener = ref.get();
            if (listener != null) {
                boolean keep = true;
                switch (action.id()) {
                    case VMAction.VM_SUSPENDED:
                        keep = listener.vmSuspended(action);
                        break;
                    case VMAction.VM_NOT_SUSPENDED:
                        keep = listener.vmNotSuspended(action);
                        break;
                }
                if (!keep) {
                    iter.remove();
                }
            } else {
                // Listener is unreachable; clean up
                iter.remove();
            }
        }

        notifyingListeners = false;
    }
}
 
Example 12
private LayoutOrder createLayoutOrder() {
    final Iterator<WeakReference<LayoutOrder>> iterator = mReusedItems.iterator();
    while (iterator.hasNext()) {
        final WeakReference<LayoutOrder> layoutOrderWeakReference = iterator.next();
        final LayoutOrder layoutOrder = layoutOrderWeakReference.get();
        iterator.remove();
        if (null != layoutOrder) {
            return layoutOrder;
        }
    }
    return new LayoutOrder();
}
 
Example 13
Source Project: kripton   File: LoanDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Invalidate livedata.</p>
 *
 */
public void invalidateLiveData() {
  for (WeakReference<LiveDataHandler> item: liveDatas) {
    if (item.get()!=null) {
      item.get().invalidate();
    }
  }
}
 
Example 14
Source Project: zhangshangwuda   File: MenuBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Remove a presenter from this menu. That presenter will no longer
 * receive notifications of updates to this menu's data.
 *
 * @param presenter The presenter to remove
 */
public void removeMenuPresenter(MenuPresenter presenter) {
    for (WeakReference<MenuPresenter> ref : mPresenters) {
        final MenuPresenter item = ref.get();
        if (item == null || item == presenter) {
            mPresenters.remove(ref);
        }
    }
}
 
Example 15
public static void main(String[] args) throws Exception {
    WeakReference ref = new WeakReference(test("test.jar", "test.Test"));
    try {
        int[] array = new int[1024];
        while (true) {
            array = new int[array.length << 1];
        }
    }
    catch (OutOfMemoryError error) {
        System.gc();
    }
    if (null != ref.get()) {
        throw new Error("ClassLoader is not released");
    }
}
 
Example 16
Source Project: jdk8u-jdk   File: LeakTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void test(Class<?> originalTestClass) throws Exception {
    System.out.println();
    System.out.println("TESTING " + originalTestClass.getName());
    WeakReference<ClassLoader> wr = testShadow(originalTestClass);
    System.out.println("Test passed, waiting for ClassLoader to disappear");
    long deadline = System.currentTimeMillis() + 20*1000;
    Reference<? extends ClassLoader> ref;
    while (wr.get() != null && System.currentTimeMillis() < deadline) {
        System.gc();
        Thread.sleep(100);
    }
    if (wr.get() != null)
        fail(originalTestClass.getName() + " kept ClassLoader reference");
}
 
Example 17
private Drawable getCachedDrawable(@DrawableRes int drawableRes) {
    synchronized (mDrawableCacheLock) {
        WeakReference<Drawable> drawableRef = mDrawableCaches.get(drawableRes);
        if (drawableRef != null) {
            Drawable drawable = drawableRef.get();
            if (drawable != null) {
                return drawable;
            } else {
                mDrawableCaches.remove(drawableRes);
            }
        }
    }
    return null;
}
 
Example 18
public static boolean isNodeValid(WeakReference<TileVisNode> node) {
	if (node == null || node.get() == null || node.get().isInvalid())
		return false;
	return true;
}
 
Example 19
Source Project: 365browser   File: MultiWindowUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Determines the correct ChromeTabbedActivity class to use for an incoming intent.
 * @param intent The incoming intent that is starting ChromeTabbedActivity.
 * @param context The current Context, used to retrieve the ActivityManager system service.
 * @return The ChromeTabbedActivity to use for the incoming intent.
 */
public Class<? extends ChromeTabbedActivity> getTabbedActivityForIntent(
        @Nullable Intent intent, Context context) {
    // 1. Exit early if the build version doesn't support Android N+ multi-window mode or
    // ChromeTabbedActivity2 isn't running.
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M
            || (mTabbedActivity2TaskRunning != null && !mTabbedActivity2TaskRunning)) {
        return ChromeTabbedActivity.class;
    }

    // 2. If the intent has a window id set, use that.
    if (intent != null && IntentUtils.safeHasExtra(intent, IntentHandler.EXTRA_WINDOW_ID)) {
        int windowId = IntentUtils.safeGetIntExtra(intent, IntentHandler.EXTRA_WINDOW_ID, 0);
        if (windowId == 1) return ChromeTabbedActivity.class;
        if (windowId == 2) return ChromeTabbedActivity2.class;
    }

    // 3. If only one ChromeTabbedActivity is currently in Android recents, use it.
    boolean tabbed2TaskRunning = isActivityTaskInRecents(
            ChromeTabbedActivity2.class.getName(), context);

    // Exit early if ChromeTabbedActivity2 isn't running.
    if (!tabbed2TaskRunning) {
        mTabbedActivity2TaskRunning = false;
        return ChromeTabbedActivity.class;
    }

    boolean tabbedTaskRunning = isActivityTaskInRecents(
            ChromeTabbedActivity.class.getName(), context);
    if (!tabbedTaskRunning) {
        return ChromeTabbedActivity2.class;
    }

    // 4. If only one of the ChromeTabbedActivity's is currently visible use it.
    // e.g. ChromeTabbedActivity is docked to the top of the screen and another app is docked
    // to the bottom.

    // Find the activities.
    Activity tabbedActivity = null;
    Activity tabbedActivity2 = null;
    for (WeakReference<Activity> reference : ApplicationStatus.getRunningActivities()) {
        Activity activity = reference.get();
        if (activity == null) continue;
        if (activity.getClass().equals(ChromeTabbedActivity.class)) {
            tabbedActivity = activity;
        } else if (activity.getClass().equals(ChromeTabbedActivity2.class)) {
            tabbedActivity2 = activity;
        }
    }

    // Determine if only one is visible.
    boolean tabbedActivityVisible = isActivityVisible(tabbedActivity);
    boolean tabbedActivity2Visible = isActivityVisible(tabbedActivity2);
    if (tabbedActivityVisible ^ tabbedActivity2Visible) {
        if (tabbedActivityVisible) return ChromeTabbedActivity.class;
        return ChromeTabbedActivity2.class;
    }

    // 5. Use the ChromeTabbedActivity that was resumed most recently if it's still running.
    if (mLastResumedTabbedActivity != null) {
        ChromeTabbedActivity lastResumedActivity = mLastResumedTabbedActivity.get();
        if (lastResumedActivity != null) {
            Class<?> lastResumedClassName = lastResumedActivity.getClass();
            if (tabbedTaskRunning
                    && lastResumedClassName.equals(ChromeTabbedActivity.class)) {
                return ChromeTabbedActivity.class;
            }
            if (tabbed2TaskRunning
                    && lastResumedClassName.equals(ChromeTabbedActivity2.class)) {
                return ChromeTabbedActivity2.class;
            }
        }
    }

    // 6. Default to regular ChromeTabbedActivity.
    return ChromeTabbedActivity.class;
}
 
Example 20
Source Project: WayHoo   File: TaskManager.java    License: Apache License 2.0 4 votes vote down vote up
private WorkTask getTaskById(String taskId) {
	WeakReference<WorkTask> existTaskRef = taskCache.get(taskId);
	if (existTaskRef != null)
		return existTaskRef.get();
	return null;
}