Java Code Examples for java.lang.ref.WeakReference

The following are top voted examples for showing how to use java.lang.ref.WeakReference. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: ReferenceCodec.java   View source code 7 votes vote down vote up
@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());
}
 
Example 2
Project: Krine   File: ClassManagerImpl.java   View source code 6 votes vote down vote up
/**
 * 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());
}
 
Example 3
Project: android-clean-code   File: HomePresenterUnitTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 4
Project: JewelryUI   File: ViewAnimationUtils.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
Project: QMUI_Android   File: QMUIAnimationListView.java   View source code 6 votes vote down vote up
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;
}
 
Example 6
Project: BiglyBT   File: ConfigurationManager.java   View source code 6 votes vote down vote up
/**
 * 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);
		  }
	  }
  }
}
 
Example 7
Project: incubator-netbeans   File: CallbackSystemAction.java   View source code 6 votes vote down vote up
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);
}
 
Example 8
Project: GitHub   File: AbstractQueryData.java   View source code 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 9
Project: OpenJSharp   File: OGLBlitLoops.java   View source code 6 votes vote down vote up
@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);
    }
}
 
Example 10
Project: openjdk-jdk10   File: WindowsLeak.java   View source code 6 votes vote down vote up
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");
}
 
Example 11
Project: incubator-netbeans   File: AbstractLookupTest.java   View source code 6 votes vote down vote up
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);
    
}
 
Example 12
Project: incubator-netbeans   File: TimeComponentPanel.java   View source code 6 votes vote down vote up
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);
}
 
Example 13
Project: openjdk-jdk10   File: PlatformLogger.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 14
Project: tomcat7   File: TcpPingInterceptor.java   View source code 6 votes vote down vote up
@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();
    }
    
}
 
Example 15
Project: openjdk-jdk10   File: BootstrapLogger.java   View source code 6 votes vote down vote up
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(()->{});
    }
}
 
Example 16
Project: GmArchMvvm   File: CrashUtils.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 17
Project: openjdk-jdk10   File: TCPTransport.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 18
Project: openjdk-jdk10   File: OGLBlitLoops.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 19
Project: incubator-netbeans   File: Containers.java   View source code 5 votes vote down vote up
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;
    }        
}
 
Example 20
Project: letv   File: DanmakuContext.java   View source code 5 votes vote down vote up
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);
            }
        }
    }
}
 
Example 21
Project: data-mediator   File: Property.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 22
Project: openjdk-jdk10   File: BufferStrategyPaintManager.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 23
Project: incubator-netbeans   File: NbTestCaseTest.java   View source code 5 votes vote down vote up
public void testAssertGcPasses() {
    Object o = new Object();
    WeakReference<Object> wr = new WeakReference<Object>(o);
    
    o = null;
    assertGC("The object is really not referenced", wr);
}
 
Example 24
Project: jdk8u-jdk   File: OGLBlitLoops.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 25
Project: micrometer   File: DropwizardMeterRegistry.java   View source code 5 votes vote down vote up
@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);
}
 
Example 26
Project: OkUSB   File: USB.java   View source code 5 votes vote down vote up
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);
}
 
Example 27
Project: openjdk-jdk10   File: BenchServerImpl.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 28
Project: OpenJSharp   File: ThreadReferenceImpl.java   View source code 5 votes vote down vote up
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;
            }
        }
    }
}
 
Example 29
Project: GitHub   File: MemoryLeakTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 30
Project: GitHub   File: TerminalManager.java   View source code 5 votes vote down vote up
/**
 * 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();
		}
	}
}
 
Example 31
Project: incubator-netbeans   File: ProxyPreferencesImplTest.java   View source code 5 votes vote down vote up
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));
    
}
 
Example 32
Project: holon-vaadin   File: DefaultViewProvider.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 33
Project: holon-vaadin   File: NavigatorActuator.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 34
Project: tenor-android-core   File: GifLoader.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 35
Project: letv   File: FFMpegPlayer.java   View source code 5 votes vote down vote up
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);
}
 
Example 36
Project: incubator-netbeans   File: Utils.java   View source code 5 votes vote down vote up
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));
}
 
Example 37
Project: OpenJSharp   File: WindowsDesktopManager.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 38
Project: Lucid2.0   File: AbstractPlayerStore.java   View source code 5 votes vote down vote up
@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();
        }
    }
}
 
Example 39
Project: spring-i18n-support   File: CachingMapDecorator.java   View source code 5 votes vote down vote up
/**
 * 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));
}
 
Example 40
Project: incubator-netbeans   File: ProxyPreferencesTest.java   View source code 5 votes vote down vote up
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));
    
}