Java 类java.lang.ref.WeakReference 实例源码

项目:GitHub    文件:ReferenceCodec.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    ParameterizedType paramType = (ParameterizedType) type;
    Type itemType = paramType.getActualTypeArguments()[0];

    Object itemObject = parser.parseObject(itemType);

    Type rawType = paramType.getRawType();
    if (rawType == AtomicReference.class) {
        return (T) new AtomicReference(itemObject);
    }

    if (rawType == WeakReference.class) {
        return (T) new WeakReference(itemObject);
    }

    if (rawType == SoftReference.class) {
        return (T) new SoftReference(itemObject);
    }

    throw new UnsupportedOperationException(rawType.toString());
}
项目:Krine    文件:ClassManagerImpl.java   
/**
 * Clear global class cache and notify namespaces to clear their
 * class caches.
 * <p>
 * The listener list is implemented with weak references so that we
 * will not keep every nameSpace in existence forever.
 */
@Override
protected void classLoaderChanged() {
    // clear the static caches in KrineClassManager
    clearCaches();

    Vector toRemove = new Vector(); // safely remove
    for (Enumeration e = listeners.elements(); e.hasMoreElements(); ) {
        WeakReference wr = (WeakReference) e.nextElement();
        Listener l = (Listener) wr.get();
        if (l == null)  // garbage collected
            toRemove.add(wr);
        else
            l.classLoaderChanged();
    }
    for (Enumeration e = toRemove.elements(); e.hasMoreElements(); )
        listeners.removeElement(e.nextElement());
}
项目:android-clean-code    文件:HomePresenterUnitTest.java   
@Test
public void presentHomeMetaData_with_inVaildInput_shouldNotCall_displayHomeMetaData(){
    //Given
    HomePresenter homePresenter = new HomePresenter();
    HomeResponse homeResponse = new HomeResponse();
    homeResponse.listOfFlights = null;

    HomeActivityInputSpy homeActivityInputSpy = new HomeActivityInputSpy();
    homePresenter.output = new WeakReference<HomeActivityInput>(homeActivityInputSpy);

    //When
    homePresenter.presentHomeMetaData(homeResponse);

    //Then
    Assert.assertFalse("When the valid input is passed to HomePresenter Then displayHomeMetaData should NOT be called", homeActivityInputSpy.isdisplayHomeMetaDataCalled);
}
项目:JewelryUI    文件:ViewAnimationUtils.java   
/**
 * Returns an Animator which can animate a clipping circle.
 * <p/>
 * Any shadow cast by the View will respect the circular clip from this animator.
 * <p/>
 * Only a single non-rectangular clip can be applied on a View at any time.
 * Views clipped by a circular reveal animation take priority over
 * {@link View#setClipToOutline(boolean) View Outline clipping}.
 * <p/>
 * Note that the animation returned here is a one-shot animation. It cannot
 * be re-used, and once started it cannot be paused or resumed.
 *
 * @param view        The View will be clipped to the animating circle.
 * @param centerX     The x coordinate of the center of the animating circle.
 * @param centerY     The y coordinate of the center of the animating circle.
 * @param startRadius The starting radius of the animating circle.
 * @param endRadius   The ending radius of the animating circle.
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static SupportAnimator createCircularReveal(View view,
                                                   int centerX, int centerY,
                                                   float startRadius, float endRadius) {

    if (!(view.getParent() instanceof RevealAnimator)) {
        throw new IllegalArgumentException("View must be inside RevealFrameLayout or RevealLinearLayout.");
    }

    RevealAnimator revealLayout = (RevealAnimator) view.getParent();
    revealLayout.attachRevealInfo(new RevealInfo(centerX, centerY, startRadius, endRadius,
            new WeakReference<>(view)));

    if (LOLLIPOP_PLUS) {
        return new SupportAnimatorLollipop(android.view.ViewAnimationUtils
                .createCircularReveal(view, centerX, centerY, startRadius, endRadius), revealLayout);
    }

    ObjectAnimator reveal = ObjectAnimator.ofFloat(revealLayout, CLIP_RADIUS,
            startRadius, endRadius);
    reveal.addListener(getRevealFinishListener(revealLayout));

    return new SupportAnimatorPreL(reveal, revealLayout);
}
项目:QMUI_Android    文件:QMUIAnimationListView.java   
protected ObjectAnimator alphaObjectAnimator(View view, final boolean fadeIn, long duration, boolean postBack) {
    final ObjectAnimator anim = ObjectAnimator.ofFloat(view, "alpha", fadeIn ? new float[]{
            0f, 1f} : new float[]{1f, 0f});

    anim.setDuration(duration);

    if (postBack) {
        final WeakReference<View> wr = new WeakReference<>(view);
        anim.addListener(new ManipulateAnimatorListener() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (wr.get() != null) {
                    wr.get().setAlpha(fadeIn ? 0 : 1);
                }
            }
        });
    }

    return anim;
}
项目:BiglyBT    文件:ConfigurationManager.java   
/**
 * Explicitly removing a weak ParameterListener prevents it from being fired
 * after being de-referenced, but before GC'd
 */
public void removeWeakParameterListener(String parameter, ParameterListener listener) {
    synchronized (weakParameterListenerz) {
      List<WeakReference<ParameterListener>> list = weakParameterListenerz.get(parameter);
      if ( list != null ){
          for (Iterator<WeakReference<ParameterListener>> iterator = list.iterator(); iterator.hasNext(); ) {
              ParameterListener existing = iterator.next().get();
              if (existing == null) {
                iterator.remove();
              } else if (existing == listener) {
                iterator.remove();
                break;
              }
          }
          if (list.size() == 0) {
            weakParameterListenerz.remove(parameter);
          }
      }
  }
}
项目:incubator-netbeans    文件:CallbackSystemAction.java   
public void attach(Action action) {
    Reference<Action> d = delegate;

    if ((d == null) || (d.get() == action)) {
        return;
    }

    Action prev = d.get();

    // reattaches to different action
    if (prev != null) {
        prev.removePropertyChangeListener(this);
    }

    this.delegate = new WeakReference<Action>(action);
    action.addPropertyChangeListener(this);
}
项目:GitHub    文件:AbstractQueryData.java   
/**
 * Note: all parameters are reset to their initial values specified in {@link QueryBuilder}.
 */
Q forCurrentThread() {
    // Process.myTid() seems to have issues on some devices (see Github #376) and Robolectric (#171):
    // We use currentThread().getId() instead (unfortunately return a long, can not use SparseArray).
    // PS.: thread ID may be reused, which should be fine because old thread will be gone anyway.
    long threadId = Thread.currentThread().getId();
    synchronized (queriesForThreads) {
        WeakReference<Q> queryRef = queriesForThreads.get(threadId);
        Q query = queryRef != null ? queryRef.get() : null;
        if (query == null) {
            gc();
            query = createQuery();
            queriesForThreads.put(threadId, new WeakReference<Q>(query));
        } else {
            System.arraycopy(initialValues, 0, query.parameters, 0, initialValues.length);
        }
        return query;
    }
}
项目:OpenJSharp    文件:OGLBlitLoops.java   
@Override
public synchronized void Transform(SurfaceData src, SurfaceData dst,
                                   Composite comp, Region clip,
                                   AffineTransform at, int hint, int srcx,
                                   int srcy, int dstx, int dsty, int width,
                                   int height){
    Blit convertsrc = Blit.getFromCache(src.getSurfaceType(),
                                        CompositeType.SrcNoEa,
                                        SurfaceType.IntArgbPre);
    // use cached intermediate surface, if available
    final SurfaceData cachedSrc = srcTmp != null ? srcTmp.get() : null;
    // convert source to IntArgbPre
    src = convertFrom(convertsrc, src, srcx, srcy, width, height, cachedSrc,
                      BufferedImage.TYPE_INT_ARGB_PRE);

    // transform IntArgbPre intermediate surface to OpenGL surface
    performop.Transform(src, dst, comp, clip, at, hint, 0, 0, dstx, dsty,
                        width, height);

    if (src != cachedSrc) {
        // cache the intermediate surface
        srcTmp = new WeakReference<>(src);
    }
}
项目:openjdk-jdk10    文件:WindowsLeak.java   
public static void main(String[] args) throws Exception {
    Robot r = new Robot();
    for (int i = 0; i < 100; i++) {
        Frame f = new Frame();
        f.pack();
        f.dispose();
    }
    r.waitForIdle();

    Disposer.addRecord(new Object(), () -> disposerPhantomComplete = true);

    while (!disposerPhantomComplete) {
        Util.generateOOME();
    }

    Vector<WeakReference<Window>> windowList =
                    (Vector<WeakReference<Window>>) AppContext.getAppContext().get(Window.class);

    if (windowList != null && !windowList.isEmpty()) {
        throw new RuntimeException("Test FAILED: Window list is not empty: " + windowList.size());
    }

    System.out.println("Test PASSED");
}
项目:incubator-netbeans    文件:AbstractLookupTest.java   
public void testResultCanBeGargageCollectedAndClearsTheResult () throws Exception {
    LkpResultCanBeGargageCollectedAndClearsTheResult lkp = new LkpResultCanBeGargageCollectedAndClearsTheResult ();
    assertSize ("24 for AbstractLookup, 8 for two ints", 32, lkp);
    synchronized (lkp) {
        Lookup.Result res = lkp.lookup (new Lookup.Template (getClass ()));
        res.allItems();

        WeakReference ref = new WeakReference (res);
        res = null;
        assertGC ("Reference can get cleared", ref);

        // wait till we 
        while (lkp.cleared == 0 && lkp.dirty == 0) {
            lkp.wait ();
        }

        assertEquals ("No dirty cleanups", 0, lkp.dirty);
        assertEquals ("One final cleanup", 1, lkp.cleared);
    }
    //assertSize ("Everything has been cleaned to original size", 32, lkp);

}
项目:incubator-netbeans    文件:TimeComponentPanel.java   
void createPopup(int x, int y, int row) {
    Object fo = jList1.getSelectedValue();
    if (fo instanceof WeakReference) fo = ((WeakReference)fo).get();
    if (fo == null) return;

    TimesCollectorPeer.Description desc = getDescForRow(fo, row);
    if (!(desc instanceof TimesCollectorPeer.ObjectCountDescripton)) return;

    final TimesCollectorPeer.ObjectCountDescripton oc = (TimesCollectorPeer.ObjectCountDescripton) desc;
    JPopupMenu popup = new JPopupMenu();
    popup.add(new AbstractAction(NbBundle.getBundle(TimeComponentPanel.class).getString("Find_refs")) {

        public void actionPerformed(ActionEvent arg0) {
            new DumpRoots(oc.getInstances());
        }
    });
    popup.show(TimeComponentPanel.this, x, y);
}
项目:openjdk-jdk10    文件:PlatformLogger.java   
/**
 * Returns a PlatformLogger of a given name.
 * @param name the name of the logger
 * @return a PlatformLogger
 */
public static synchronized PlatformLogger getLogger(String name) {
    PlatformLogger log = null;
    WeakReference<PlatformLogger> ref = loggers.get(name);
    if (ref != null) {
        log = ref.get();
    }
    if (log == null) {
        log = new PlatformLogger(PlatformLogger.Bridge.convert(
                // We pass PlatformLogger.class.getModule() (java.base)
                // rather than the actual module of the caller
                // because we want PlatformLoggers to be system loggers: we
                // won't need to resolve any resource bundles anyway.
                // Note: Many unit tests depend on the fact that
                //       PlatformLogger.getLoggerFromFinder is not caller
                //       sensitive, and this strategy ensure that the tests
                //       still pass.
                LazyLoggers.getLazyLogger(name, PlatformLogger.class.getModule())));
        loggers.put(name, new WeakReference<>(log));
    }
    return log;
}
项目:tomcat7    文件:TcpPingInterceptor.java   
@Override
public synchronized void start(int svc) throws ChannelException {
    super.start(svc);
    running = true;
    if ( thread == null && useThread) {
        thread = new PingThread();
        thread.setDaemon(true);
        String channelName = "";
        if (getChannel() instanceof GroupChannel && ((GroupChannel)getChannel()).getName() != null) {
            channelName = "[" + ((GroupChannel)getChannel()).getName() + "]";
        }
        thread.setName("TcpPingInterceptor.PingThread" + channelName +"-"+cnt.addAndGet(1));
        thread.start();
    }

    //acquire the interceptors to invoke on send ping events
    ChannelInterceptor next = getNext();
    while ( next != null ) {
        if ( next instanceof TcpFailureDetector ) 
            failureDetector = new WeakReference<TcpFailureDetector>((TcpFailureDetector)next);
        if ( next instanceof StaticMembershipInterceptor ) 
            staticMembers = new WeakReference<StaticMembershipInterceptor>((StaticMembershipInterceptor)next);
        next = next.getNext();
    }

}
项目:openjdk-jdk10    文件:BootstrapLogger.java   
static void awaitPendingTasks() {
    WeakReference<ExecutorService> ref = executorRef;
    ExecutorService executor = ref == null ? null : ref.get();
    if (ref == null) {
        synchronized(BootstrapExecutors.class) {
            ref = executorRef;
            executor = ref == null ? null : ref.get();
        }
    }
    if (executor != null) {
        // since our executor uses a FIFO and has a single thread
        // then awaiting the execution of its pending tasks can be done
        // simply by registering a new task and waiting until it
        // completes. This of course would not work if we were using
        // several threads, but we don't.
        join(()->{});
    }
}
项目:GmArchMvvm    文件:CrashUtils.java   
/**
 * initialization
 * <p>Need to add permission {@code <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>}</p>
 *
 * @param crashDir Crash file storage directory
 * @return {@code true}: Initialized successfully<br>{@code false}: initialization failed
 */
public static boolean init(Application application, final String crashDir) {
    if (mApplication == null)
        mApplication = new WeakReference<>(application);
    if (isSpace(crashDir)) {
        dir = null;
    } else {
        dir = crashDir.endsWith(FILE_SEP) ? dir : dir + FILE_SEP;
    }
    if (mInitialized)
        return true;
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            && mApplication.get().getExternalCacheDir() != null) {
        defaultDir = mApplication.get().getExternalCacheDir() + FILE_SEP + "crash" + FILE_SEP;
    } else {
        defaultDir = mApplication.get().getCacheDir() + FILE_SEP + "crash" + FILE_SEP;
    }
    Thread.setDefaultUncaughtExceptionHandler(UNCAUGHT_EXCEPTION_HANDLER);
    return mInitialized = true;
}
项目:openjdk-jdk10    文件:TCPTransport.java   
/**
 * Returns a <I>Channel</I> that generates connections to the
 * endpoint <I>ep</I>. A Channel is an object that creates and
 * manages connections of a particular type to some particular
 * address space.
 * @param ep the endpoint to which connections will be generated.
 * @return the channel or null if the transport cannot
 * generate connections to this endpoint
 */
public TCPChannel getChannel(Endpoint ep) {
    TCPChannel ch = null;
    if (ep instanceof TCPEndpoint) {
        synchronized (channelTable) {
            Reference<TCPChannel> ref = channelTable.get(ep);
            if (ref != null) {
                ch = ref.get();
            }
            if (ch == null) {
                TCPEndpoint tcpEndpoint = (TCPEndpoint) ep;
                ch = new TCPChannel(this, tcpEndpoint);
                channelTable.put(tcpEndpoint,
                                 new WeakReference<TCPChannel>(ch));
            }
        }
    }
    return ch;
}
项目:openjdk-jdk10    文件:OGLBlitLoops.java   
public synchronized void Blit(SurfaceData src, SurfaceData dst,
                              Composite comp, Region clip,
                              int sx, int sy, int dx, int dy,
                              int w, int h)
{
    Blit convertsrc = Blit.getFromCache(src.getSurfaceType(),
                                        CompositeType.SrcNoEa,
                                        SurfaceType.IntArgbPre);

    SurfaceData cachedSrc = null;
    if (srcTmp != null) {
        // use cached intermediate surface, if available
        cachedSrc = srcTmp.get();
    }

    // convert source to IntArgbPre
    src = convertFrom(convertsrc, src, sx, sy, w, h,
                      cachedSrc, BufferedImage.TYPE_INT_ARGB_PRE);

    // copy IntArgbPre intermediate surface to OpenGL surface
    performop.Blit(src, dst, comp, clip,
                   0, 0, dx, dy, w, h);

    if (src != cachedSrc) {
        // cache the intermediate surface
        srcTmp = new WeakReference<>(src);
    }
}
项目:incubator-netbeans    文件:Containers.java   
public static OperationContainer<InstallSupport> forAvailable() {
    synchronized(Containers.class) {
        OperationContainer<InstallSupport> container = null;
        if (INSTALL != null) {
            container = INSTALL.get();
        }
        if (container == null) {
            container  = OperationContainer.createForInstall();
            INSTALL = new WeakReference<OperationContainer<InstallSupport>>(container);
        }
        return container;
    }        
}
项目:letv    文件:DanmakuContext.java   
private void notifyConfigureChanged(DanmakuConfigTag tag, Object... values) {
    if (this.mCallbackList != null) {
        for (WeakReference<ConfigChangedCallback> configReferer : this.mCallbackList) {
            ConfigChangedCallback cb = (ConfigChangedCallback) configReferer.get();
            if (cb != null) {
                cb.onDanmakuConfigChanged(this, tag, values);
            }
        }
    }
}
项目:data-mediator    文件:Property.java   
/**
 * get base the property type.
 * @return the base type.
 * @see #getComplexType()
 */
public Class<?> getType() {
     //this object may be const, so weak reference ,
     // even if the Class very likely exist loaded all the time.
     if(mWeakClass == null || mWeakClass.get() == null){
          mWeakClass = new WeakReference<Class<?>>(getType0());
     }
     return mWeakClass.get();
}
项目:openjdk-jdk10    文件:BufferStrategyPaintManager.java   
/**
 * Returns the BufferStartegy.  This will return null if
 * the BufferStartegy hasn't been created and <code>create</code> is
 * false, or if there is a problem in creating the
 * <code>BufferStartegy</code>.
 *
 * @param create If true, and the BufferStartegy is currently null,
 *               one will be created.
 */
public BufferStrategy getBufferStrategy(boolean create) {
    BufferStrategy bs = (weakBS == null) ? null : weakBS.get();
    if (bs == null && create) {
        bs = createBufferStrategy();
        if (bs != null) {
            weakBS = new WeakReference<BufferStrategy>(bs);
        }
        if (LOGGER.isLoggable(PlatformLogger.Level.FINER)) {
            LOGGER.finer("getBufferStrategy: created bs: " + bs);
        }
    }
    return bs;
}
项目:incubator-netbeans    文件:NbTestCaseTest.java   
public void testAssertGcPasses() {
    Object o = new Object();
    WeakReference<Object> wr = new WeakReference<Object>(o);

    o = null;
    assertGC("The object is really not referenced", wr);
}
项目:jdk8u-jdk    文件:OGLBlitLoops.java   
private synchronized void complexClipBlit(SurfaceData src, SurfaceData dst,
                                          Composite comp, Region clip,
                                          int sx, int sy, int dx, int dy,
                                          int w, int h) {
    SurfaceData cachedSrc = null;
    if (srcTmp != null) {
        // use cached intermediate surface, if available
        cachedSrc = srcTmp.get();
    }

    // We can convert argb_pre data from OpenGL surface in two places:
    // - During OpenGL surface -> SW blit
    // - During SW -> SW blit
    // The first one is faster when we use opaque OGL surface, because in
    // this case we simply skip conversion and use color components as is.
    // Because of this we align intermediate buffer type with type of
    // destination not source.
    final int type = typeval == OGLSurfaceData.PF_INT_ARGB_PRE ?
                     BufferedImage.TYPE_INT_ARGB_PRE :
                     BufferedImage.TYPE_INT_ARGB;

    src = convertFrom(this, src, sx, sy, w, h, cachedSrc, type);

    // copy intermediate SW to destination SW using complex clip
    final Blit performop = Blit.getFromCache(src.getSurfaceType(),
                                             CompositeType.SrcNoEa,
                                             dst.getSurfaceType());
    performop.Blit(src, dst, comp, clip, 0, 0, dx, dy, w, h);

    if (src != cachedSrc) {
        // cache the intermediate surface
        srcTmp = new WeakReference<>(src);
    }
}
项目:micrometer    文件:DropwizardMeterRegistry.java   
@Override
protected <T> io.micrometer.core.instrument.Gauge newGauge(Meter.Id id, T obj, ToDoubleFunction<T> f) {
    final WeakReference<T> ref = new WeakReference<>(obj);
    Gauge<Double> gauge = () -> {
        T obj2 = ref.get();
        return obj2 != null ? f.applyAsDouble(ref.get()) : Double.NaN;
    };
    registry.register(hierarchicalName(id), gauge);
    return new DropwizardGauge(id, gauge);
}
项目:OkUSB    文件:USB.java   
private USB(Activity ctx, USBBuilder builder) {
    BAUD_RATE = builder.BAUD_RATE;
    DATA_BITS = builder.DATA_BITS;
    STOP_BITS = builder.STOP_BITS;
    PARITY = builder.PARITY;
    MAX_READ_BYTES = builder.MAX_READ_BYTES;
    READ_DURATION = builder.READ_DURATION;
    DTR = builder.DTR;
    RTS = builder.RTS;

    this.ctx = new WeakReference<Activity>(ctx);
    usbManager = (UsbManager) ctx.getSystemService(Context.USB_SERVICE);
    initReadThread(this.ctx);
}
项目:openjdk-jdk10    文件:BenchServerImpl.java   
/**
 * Uses the given remote object factory to create a new remote object on
 * the server side.
 */
public Remote create(BenchServer.RemoteObjectFactory factory)
    throws RemoteException
{
    Remote impl = factory.create();
    implTable.put(RemoteObject.toStub(impl), new WeakReference(impl));
    return impl;
}
项目:OpenJSharp    文件:ThreadReferenceImpl.java   
void removeListener(ThreadListener listener) {
    synchronized (vm.state()) {
        Iterator<WeakReference<ThreadListener>> iter = listeners.iterator();
        while (iter.hasNext()) {
            WeakReference<ThreadListener> ref = iter.next();
            if (listener.equals(ref.get())) {
                iter.remove();
                break;
            }
        }
    }
}
项目:GitHub    文件:MemoryLeakTest.java   
@Test
public void test() {
    TestViewImplementation viewImplementation = new TestViewImplementation();

    viewImplementation.delegate = new MvpDelegate<>(viewImplementation);

    viewImplementation.delegate.onCreate(new Bundle());

    viewImplementation.delegate.onDestroy();

    WeakReference viewImplementationReference = new WeakReference(viewImplementation);
    WeakReference presenterReference = new WeakReference(viewImplementation.presenter);

    /**
     * Remove local reference to this object. Test will been failed if reference to the implemented view or
     * to presenter was being saved in Moxy
     */
    //noinspection UnusedAssignment
    viewImplementation = null;

    long delay = 0;

    while (delay < TimeUnit.SECONDS.toMillis(2)) {
        System.gc();

        if (viewImplementationReference.get() == null && presenterReference.get() == null) {
            return;
        }

        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        delay += 100;
    }

    assertTrue(false);
}
项目:GitHub    文件:TerminalManager.java   
/**
 * Insert request into reconnect queue to be executed either immediately
 * or later when connectivity is restored depending on whether we're
 * currently connected.
 *
 * @param bridge the TerminalBridge to reconnect when possible
 */
public void requestReconnect(TerminalBridge bridge) {
    synchronized (mPendingReconnect) {
        mPendingReconnect.add(new WeakReference<TerminalBridge>(bridge));
        if (!bridge.isUsingNetwork() ||
                connectivityManager.isConnected()) {
            reconnectPending();
        }
    }
}
项目:incubator-netbeans    文件:ProxyPreferencesImplTest.java   
public void testTreeGCed() throws BackingStoreException {
    String [] newTree = new String [] {
        "R.CodeStyle.project.expand-tabs=true",
        "R.CodeStyle.project.indent-shift-width=3",
        "R.CodeStyle.project.spaces-per-tab=3",
        "R.CodeStyle.project.tab-size=5",
        "R.CodeStyle.project.text-limit-width=77",
        "R.CodeStyle.usedProfile=project",
        "R.text.x-ruby.CodeStyle.project.indent-shift-width=2",
        "R.text.x-ruby.CodeStyle.project.spaces-per-tab=2",
        "R.text.x-ruby.CodeStyle.project.tab-size=2",
    };

    Preferences orig = Preferences.userRoot().node(getName());

    Object treeToken = new Object();
    Preferences test = ProxyPreferencesImpl.getProxyPreferences(treeToken, orig);
    write(test, newTree);
    checkContains(test, newTree, "Test");

    Reference<Object> treeTokenRef = new WeakReference<Object>(treeToken);
    Reference<Preferences> testRef = new WeakReference<Preferences>(test);
    treeToken = null;
    test = null;
    assertGC("Tree token was not GCed", treeTokenRef, Collections.singleton(this));
    // touch the WeakHashMap to expungeStaleEntries
    Object dummyToken = new Object();
    ProxyPreferencesImpl dummyPrefs = ProxyPreferencesImpl.getProxyPreferences(dummyToken, orig);
    assertGC("Test preferences were not GCed", testRef, Collections.singleton(this));

}
项目:holon-vaadin    文件:DefaultViewProvider.java   
/**
 * Check if staetful view instance was already created for given UI and view class and, if found, returns it.
 * @param ui UI
 * @param viewClass View class
 * @return View instance, or <code>null</code> if not found
 */
protected View getStatefulViewInstance(UI ui, Class<? extends View> viewClass) {
    Map<Class<? extends View>, WeakReference<View>> views = statefulViews.get(ui);
    if (views != null) {
        WeakReference<View> vr = views.get(viewClass);
        if (vr != null) {
            return vr.get();
        }
    }
    return null;
}
项目:holon-vaadin    文件:NavigatorActuator.java   
/**
 * Get the view navigation window associated to given state, if present.
 * @param navigationState Navigation state
 * @return view navigation window, <code>null</code> if not present
 */
protected Window getViewWindow(String navigationState) {
    WeakReference<Window> wr = viewWindows.get(navigationState);
    if (wr != null) {
        return wr.get();
    }
    return null;
}
项目:tenor-android-core    文件:GifLoader.java   
/**
 * Uses Glide to load a gif or image into an ImageView
 *
 * @param weakRef the {@link WeakReference} of a given subclass of {@link Context}
 * @param params  the {@link GlideTaskParams}
 */
public static <CTX extends Context, T extends ImageView> void loadGif(@NonNull WeakReference<CTX> weakRef,
                                                                      @NonNull GlideTaskParams<T> params) {

    if (!AbstractWeakReferenceUtils.isAlive(weakRef)) {
        return;
    }

    GifRequestBuilder<String> requestBuilder = Glide.with(weakRef.get()).load(params.getPath()).asGif()
            .diskCacheStrategy(DiskCacheStrategy.ALL);

    load(applyDimens(requestBuilder, params), params);
}
项目:letv    文件:FFMpegPlayer.java   
public static int fillInputBuffer(Object mediaplayer_ref, byte[] data, long pts, int flush) throws IOException {
    FFMpegPlayer mp = (FFMpegPlayer) ((WeakReference) mediaplayer_ref).get();
    if (mp == null || mp.mVideoDecoder == null) {
        return -1;
    }
    return mp.mVideoDecoder.fillInputBuffer(data, pts, flush);
}
项目:incubator-netbeans    文件:Utils.java   
public static void startTest (String name, Collection c) {
    if (collections == null) {
        // init
        collections = new HashMap<String,WeakReference> ();
        start ();
    }
    collections.put (name, new WeakReference<Collection> (c));
}
项目:OpenJSharp    文件:WindowsDesktopManager.java   
public void activateFrame(JInternalFrame f) {
    JInternalFrame currentFrame = currentFrameRef != null ?
        currentFrameRef.get() : null;
    try {
        super.activateFrame(f);
        if (currentFrame != null && f != currentFrame) {
            // If the current frame is maximized, transfer that
            // attribute to the frame being activated.
            if (currentFrame.isMaximum() &&
                (f.getClientProperty("JInternalFrame.frameType") !=
                "optionDialog") ) {
                //Special case.  If key binding was used to select next
                //frame instead of minimizing the icon via the minimize
                //icon.
                if (!currentFrame.isIcon()) {
                    currentFrame.setMaximum(false);
                    if (f.isMaximizable()) {
                        if (!f.isMaximum()) {
                            f.setMaximum(true);
                        } else if (f.isMaximum() && f.isIcon()) {
                            f.setIcon(false);
                        } else {
                            f.setMaximum(false);
                        }
                    }
                }
            }
            if (currentFrame.isSelected()) {
                currentFrame.setSelected(false);
            }
        }

        if (!f.isSelected()) {
            f.setSelected(true);
        }
    } catch (PropertyVetoException e) {}
    if (f != currentFrame) {
        currentFrameRef = new WeakReference<JInternalFrame>(f);
    }
}
项目:Lucid2.0    文件:AbstractPlayerStore.java   
@Override
public void removeVisitor(MapleCharacter visitor) {
    final byte slot = getVisitorSlot(visitor);
    boolean shouldUpdate = getFreeSlot() == -1;
    if (slot > 0) {
        broadcastToVisitors(PlayerShopPacket.shopVisitorLeave(slot), slot);
        chrs[slot - 1] = new WeakReference<>(null);
        if (shouldUpdate) {
            update();
        }
    }
}
项目:spring-i18n-support    文件:CachingMapDecorator.java   
/**
 * Put an object into the cache, possibly wrapping it with a weak
 * reference.
 *
 * @see #useWeakValue(Object, Object)
 */
public V put(K key, V value)
{
    Object newValue = value;
    if (value == null)
    {
        newValue = NULL_VALUE;
    }
    else if (useWeakValue(key, value))
    {
        newValue = new WeakReference<Object>(newValue);
    }
    return unwrapReturnValue(this.targetMap.put(key, newValue));
}
项目:incubator-netbeans    文件:ProxyPreferencesTest.java   
public void testTreeGCed() throws BackingStoreException {
    String [] newTree = new String [] {
        "R.CodeStyle.project.expand-tabs=true",
        "R.CodeStyle.project.indent-shift-width=3",
        "R.CodeStyle.project.spaces-per-tab=3",
        "R.CodeStyle.project.tab-size=5",
        "R.CodeStyle.project.text-limit-width=77",
        "R.CodeStyle.usedProfile=project",
        "R.text.x-ruby.CodeStyle.project.indent-shift-width=2",
        "R.text.x-ruby.CodeStyle.project.spaces-per-tab=2",
        "R.text.x-ruby.CodeStyle.project.tab-size=2",
    };

    Preferences orig = Preferences.userRoot().node(getName());

    Object treeToken = new Object();
    Preferences test = ProxyPreferences.getProxyPreferences(treeToken, orig);
    write(test, newTree);
    checkContains(test, newTree, "Test");

    Reference<Object> treeTokenRef = new WeakReference<Object>(treeToken);
    Reference<Preferences> testRef = new WeakReference<Preferences>(test);
    treeToken = null;
    test = null;
    assertGC("Tree token was not GCed", treeTokenRef, Collections.singleton(this));
    // touch the WeakHashMap to expungeStaleEntries
    Object dummyToken = new Object();
    ProxyPreferences dummyPrefs = ProxyPreferences.getProxyPreferences(dummyToken, orig);
    assertGC("Test preferences were not GCed", testRef, Collections.singleton(this));

}