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

The following examples show how to use java.lang.ref.WeakReference#get() . 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
Source File: MenuBuilder.java    From Libraries-for-Android-Developers with MIT License 6 votes vote down vote up
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 2
Source File: HeapMemoryAllocator.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
@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 3
Source File: ConsoleColorCache.java    From Pydev with 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 4
Source File: PythonNatureListenersManager.java    From Pydev with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 5
Source File: DownloadController.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
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 6
Source File: BundleFileSystemProvider.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
@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 7
Source File: ChromeLifetimeController.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
@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 8
Source File: BitmapUtils.java    From android with 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 9
Source File: Test7064279.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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 10
Source File: SkinCompatUserThemeManager.java    From Android-skin-support with MIT License 5 votes vote down vote up
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 11
Source File: LeakTest.java    From jdk8u-jdk with 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 12
Source File: CloseableThreadLocal.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
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 13
Source File: MenuBuilder.java    From zhangshangwuda with 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 14
Source File: LoanDaoImpl.java    From kripton with 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 15
Source File: CarouselLayoutManager.java    From CarouselLayoutManager with Apache License 2.0 5 votes vote down vote up
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 16
Source File: VMState.java    From jdk8u_jdk with 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 17
Source File: DaoPersonImpl.java    From kripton with 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 18
Source File: VisNetHandler.java    From AdvancedMod with GNU General Public License v3.0 4 votes vote down vote up
public static boolean isNodeValid(WeakReference<TileVisNode> node) {
	if (node == null || node.get() == null || node.get().isInvalid())
		return false;
	return true;
}
 
Example 19
Source File: MultiWindowUtils.java    From 365browser with 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 File: TaskManager.java    From WayHoo with 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;
}