当前位置: 首页>>代码示例>>Java>>正文


Java WeakReference类代码示例

本文整理汇总了Java中java.lang.ref.WeakReference的典型用法代码示例。如果您正苦于以下问题:Java WeakReference类的具体用法?Java WeakReference怎么用?Java WeakReference使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


WeakReference类属于java.lang.ref包,在下文中一共展示了WeakReference类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: deserialze

import java.lang.ref.WeakReference; //导入依赖的package包/类
@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());
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:23,代码来源:ReferenceCodec.java

示例2: classLoaderChanged

import java.lang.ref.WeakReference; //导入依赖的package包/类
/**
 * 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());
}
 
开发者ID:imkiva,项目名称:Krine,代码行数:25,代码来源:ClassManagerImpl.java

示例3: presentHomeMetaData_with_inVaildInput_shouldNotCall_displayHomeMetaData

import java.lang.ref.WeakReference; //导入依赖的package包/类
@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);
}
 
开发者ID:kmmraj,项目名称:android-clean-code,代码行数:17,代码来源:HomePresenterUnitTest.java

示例4: createCircularReveal

import java.lang.ref.WeakReference; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:SimonCherryGZ,项目名称:JewelryUI,代码行数:43,代码来源:ViewAnimationUtils.java

示例5: alphaObjectAnimator

import java.lang.ref.WeakReference; //导入依赖的package包/类
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;
}
 
开发者ID:QMUI,项目名称:QMUI_Android,代码行数:21,代码来源:QMUIAnimationListView.java

示例6: removeWeakParameterListener

import java.lang.ref.WeakReference; //导入依赖的package包/类
/**
 * 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);
		  }
	  }
  }
}
 
开发者ID:BiglySoftware,项目名称:BiglyBT,代码行数:24,代码来源:ConfigurationManager.java

示例7: attach

import java.lang.ref.WeakReference; //导入依赖的package包/类
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);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:18,代码来源:CallbackSystemAction.java

示例8: forCurrentThread

import java.lang.ref.WeakReference; //导入依赖的package包/类
/**
 * 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;
    }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:22,代码来源:AbstractQueryData.java

示例9: Transform

import java.lang.ref.WeakReference; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:25,代码来源:OGLBlitLoops.java

示例10: main

import java.lang.ref.WeakReference; //导入依赖的package包/类
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");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:WindowsLeak.java

示例11: testResultCanBeGargageCollectedAndClearsTheResult

import java.lang.ref.WeakReference; //导入依赖的package包/类
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);
    
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:23,代码来源:AbstractLookupTest.java

示例12: createPopup

import java.lang.ref.WeakReference; //导入依赖的package包/类
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);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:19,代码来源:TimeComponentPanel.java

示例13: getLogger

import java.lang.ref.WeakReference; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:27,代码来源:PlatformLogger.java

示例14: start

import java.lang.ref.WeakReference; //导入依赖的package包/类
@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();
    }
    
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:27,代码来源:TcpPingInterceptor.java

示例15: awaitPendingTasks

import java.lang.ref.WeakReference; //导入依赖的package包/类
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(()->{});
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:19,代码来源:BootstrapLogger.java


注:本文中的java.lang.ref.WeakReference类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。