java.lang.ref.WeakReference Java Examples

The following examples show how to use java.lang.ref.WeakReference. 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: ReceivedTokenCallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof DelegationCallback) {
            DelegationCallback callback = (DelegationCallback) callbacks[i];
            Message message = callback.getCurrentMessage();
            
            if (message != null 
                && message.get(PhaseInterceptorChain.PREVIOUS_MESSAGE) != null) {
                WeakReference<SoapMessage> wr = 
                    (WeakReference<SoapMessage>)
                        message.get(PhaseInterceptorChain.PREVIOUS_MESSAGE);
                SoapMessage previousSoapMessage = wr.get();
                Element token = getTokenFromMessage(previousSoapMessage);
                if (token != null) {
                    callback.setToken(token);
                }
            }
            
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #2
Source File: RaygunErrorMessage.java    From raygun4java with MIT License 6 votes vote down vote up
public RaygunErrorMessage(Throwable throwable) {
    if (throwable == null) {
        return;
    }

    this.throwable = new WeakReference<Throwable>(throwable);
    message = throwable.getClass().getSimpleName();
    String throwableMessage = throwable.getMessage();
    if (throwableMessage != null) {
        message = message.concat(": ").concat(throwableMessage);
    }
    className = throwable.getClass().getCanonicalName();

    if (throwable.getCause() != null) {
        innerError = new RaygunErrorMessage(throwable.getCause());
    }

    StackTraceElement[] ste = throwable.getStackTrace();
    stackTrace = new RaygunErrorStackTraceLineMessage[ste.length];

    for (int i = 0; i < ste.length; i++) {
        stackTrace[i] = new RaygunErrorStackTraceLineMessage(ste[i]);
    }
}
 
Example #3
Source File: Window.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private void setOwnedWindowsAlwaysOnTop(boolean alwaysOnTop) {
    WeakReference<Window>[] ownedWindowArray;
    synchronized (ownedWindowList) {
        ownedWindowArray = new WeakReference[ownedWindowList.size()];
        ownedWindowList.copyInto(ownedWindowArray);
    }

    for (WeakReference<Window> ref : ownedWindowArray) {
        Window window = ref.get();
        if (window != null) {
            try {
                window.setAlwaysOnTop(alwaysOnTop);
            } catch (SecurityException ignore) {
            }
        }
    }
}
 
Example #4
Source File: OGLBlitLoops.java    From openjdk-jdk8u with GNU General Public License v2.0 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 #5
Source File: TCPTransport.java    From jdk8u-dev-jdk with GNU General Public License v2.0 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 #6
Source File: GradientPaintContext.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
static synchronized void putCachedRaster(ColorModel cm, Raster ras) {
    if (cached != null) {
        Raster cras = (Raster) cached.get();
        if (cras != null) {
            int cw = cras.getWidth();
            int ch = cras.getHeight();
            int iw = ras.getWidth();
            int ih = ras.getHeight();
            if (cw >= iw && ch >= ih) {
                return;
            }
            if (cw * ch >= iw * ih) {
                return;
            }
        }
    }
    cachedModel = cm;
    cached = new WeakReference<>(ras);
}
 
Example #7
Source File: PuzzleActivity.java    From imsdk-android with MIT License 6 votes vote down vote up
public static void startWithPaths(Fragment fragment, ArrayList<String> paths, String puzzleSaveDirPath, String puzzleSaveNamePrefix, int requestCode, boolean replaceCustom, @NonNull ImageEngine imageEngine) {
    if (null != toClass) {
        toClass.clear();
        toClass = null;
    }
    if (Setting.imageEngine != imageEngine) {
        Setting.imageEngine = imageEngine;
    }
    Intent intent = new Intent(fragment.getActivity(), PuzzleActivity.class);
    intent.putExtra(Key.PUZZLE_FILE_IS_PHOTO, false);
    intent.putStringArrayListExtra(Key.PUZZLE_FILES, paths);
    intent.putExtra(Key.PUZZLE_SAVE_DIR, puzzleSaveDirPath);
    intent.putExtra(Key.PUZZLE_SAVE_NAME_PREFIX, puzzleSaveNamePrefix);
    if (replaceCustom) {
        toClass = new WeakReference<Class<? extends Activity>>(fragment.getActivity().getClass());
    }
    fragment.startActivityForResult(intent, requestCode);
}
 
Example #8
Source File: ShareActivity.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the ChromeActivity that called the share intent picker.
 */
private ChromeActivity getTriggeringActivity() {
    int triggeringTaskId =
            IntentUtils.safeGetIntExtra(getIntent(), ShareHelper.EXTRA_TASK_ID, 0);
    List<WeakReference<Activity>> activities = ApplicationStatus.getRunningActivities();
    ChromeActivity triggeringActivity = null;
    for (int i = 0; i < activities.size(); i++) {
        Activity activity = activities.get(i).get();
        if (activity == null) continue;

        if (activity.getTaskId() == triggeringTaskId && activity instanceof ChromeActivity) {
            return (ChromeActivity) activity;
        }
    }
    return null;
}
 
Example #9
Source File: MultipleGradientPaintContext.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Took this cacheRaster code from GradientPaint. It appears to recycle
 * rasters for use by any other instance, as long as they are sufficiently
 * large.
 */
private static synchronized void putCachedRaster(ColorModel cm,
                                                 Raster ras)
{
    if (cached != null) {
        Raster cras = (Raster) cached.get();
        if (cras != null) {
            int cw = cras.getWidth();
            int ch = cras.getHeight();
            int iw = ras.getWidth();
            int ih = ras.getHeight();
            if (cw >= iw && ch >= ih) {
                return;
            }
            if (cw * ch >= iw * ih) {
                return;
            }
        }
    }
    cachedModel = cm;
    cached = new WeakReference<Raster>(ras);
}
 
Example #10
Source File: LoginDialog.java    From 4pdaClient-plus with Apache License 2.0 6 votes vote down vote up
LoginTask(Context context,
          String login, String password, Boolean privacy,
          String capVal, String capTime, String capSig) {
    mContext = new WeakReference<>(context);
    this.login = login;
    this.password = password;
    this.privacy = privacy;
    this.capVal = capVal;
    this.capTime = capTime;
    this.capSig = capSig;
    dialog = new MaterialDialog.Builder(mContext.get())
            .progress(true, 0)
            .cancelable(false)
            .content(R.string.performing_login)
            .build();
}
 
Example #11
Source File: AutomaticAcquisition.java    From ans-android-sdk with GNU General Public License v3.0 6 votes vote down vote up
private void activityStop(WeakReference<Activity> activity) {
    if (activity != null) {
        Context context = activity.get();
        if (context != null) {
            // 热图部分逻辑不能在子线程执行
            if (AgentProcess.getInstance().getConfig().isAutoHeatMap()) {
                checkLayoutListener(activity, false);
            }

            // 单队列线程执行
            AThreadPool.asyncMiddlePriorityExecutor(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 调用AppEnd
                        appEnd();
                    }catch (Throwable ignore) {
                        ExceptionUtil.exceptionThrow(ignore);
                    }
                }
            });
        }
    }
}
 
Example #12
Source File: BitmapTools.java    From volley with Apache License 2.0 6 votes vote down vote up
public ImageContainer doDisplay(View v, final String uri, BitmapDisplayConfig displayConfig, LoadingListener loadingListener) {
    	if (displayConfig == null) {
            displayConfig = mDisplayConfig;
        }
        final WeakReference<View> ref = new WeakReference<View>(v);
        final BitmapDisplayConfig curDisplayConfig = displayConfig;
        return doDisplay(ref.get(), uri, curDisplayConfig, new ImageListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                showImg(ref.get(), null, curDisplayConfig, false, false);
                mDisplayer.loadFailDisplay(ref.get(), curDisplayConfig);
            }

            @Override
            public void onResponse(ImageContainer response, boolean isImmediate) {
                if (response.getBitmap() == null) {
                    mDisplayer.loadDefaultDisplay(ref.get(), curDisplayConfig);
                } else {
                    curDisplayConfig.isImmediate = isImmediate;
                    mDisplayer.loadCompletedisplay(ref.get(), response.getBitmap(), curDisplayConfig);
                }
            }
        }, loadingListener);
    }
 
Example #13
Source File: ProtifyApplication.java    From sbt-android-protify with Apache License 2.0 6 votes vote down vote up
@TargetApi(24)
static void install(String externalResourceFile) {
    try {
        AssetManager newAssetManager = createAssetManager(externalResourceFile);

        // Find the singleton instance of ResourcesManager
        Class<?> clazz = Class.forName("android.app.ResourcesManager");
        Method mGetInstance = clazz.getDeclaredMethod("getInstance");
        mGetInstance.setAccessible(true);
        Object resourcesManager = mGetInstance.invoke(null);

        // Iterate over all known Resources objects
        Field mResourceReferences = clazz.getDeclaredField("mResourceReferences");
        mResourceReferences.setAccessible(true);
        @SuppressWarnings("unchecked")
        Collection<WeakReference<Resources>> references =
                (Collection<WeakReference<Resources>>) mResourceReferences.get(resourcesManager);

        setAssetManager(references, newAssetManager);
    } catch (IllegalAccessException | NoSuchFieldException | NoSuchMethodException |
            ClassNotFoundException | InvocationTargetException | InstantiationException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #14
Source File: Window.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
private void addToWindowList() {
    synchronized (Window.class) {
        @SuppressWarnings("unchecked")
        Vector<WeakReference<Window>> windowList = (Vector<WeakReference<Window>>)appContext.get(Window.class);
        if (windowList == null) {
            windowList = new Vector<WeakReference<Window>>();
            appContext.put(Window.class, windowList);
        }
        windowList.add(weakThis);
    }
}
 
Example #15
Source File: TreeModelNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void applyChildren(final Object[] ch, RefreshingInfo refreshInfo, boolean doSetObject) {
    //System.err.println(this.hashCode()+" applyChildren("+refreshSubNodes+")");
    //System.err.println("applyChildren("+Arrays.toString(ch)+", "+doSetObject+")");
    int i, k = ch.length; 
    for (i = 0; i < k; i++) {
        if (ch [i] == null) {
            throw new NullPointerException("Null child at index "+i+", parent: "+object+", model: "+model+"\nAll children are: "+Arrays.toString(ch));
        }
        if (doSetObject) {
            WeakReference<TreeModelNode> wr;
            synchronized (objectToNode) {
                wr = objectToNode.get(ch [i]);
            }
            if (wr == null) continue;
            TreeModelNode tmn = wr.get ();
            if (tmn == null) continue;
            if (refreshInfo == null || refreshInfo.isRefreshSubNodes(ch[i])) {
                tmn.setObject (ch [i]);
            } else {
                tmn.setObjectNoRefresh(ch[i]);
            }
        }
    }
    setKeys (ch);

    SwingUtilities.invokeLater (new Runnable () {
        public void run () {
            int i, k = ch.length;
            for (i = 0; i < k; i++)
                expandIfSetToExpanded(ch[i]);
        }
    });
}
 
Example #16
Source File: ID.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static <T extends ID> T getObjCObjectFor(final JObjCRuntime runtime, final long objPtr){
    if (objPtr == 0) return null;

    final WeakReference cachedObj = objectCache.get().get(objPtr);
    if(cachedObj != null && cachedObj.get() != null) return (T) cachedObj.get();

    final long clsPtr = NSClass.getClass(objPtr);

    final T newObj = (T) (runtime.subclassing.isUserClass(clsPtr) ?
            Subclassing.getJObjectFromIVar(objPtr)
            : createNewObjCObjectFor(runtime, objPtr, clsPtr));

    objectCache.get().put(objPtr, new WeakReference(newObj));
    return newObj;
}
 
Example #17
Source File: AbstractDimensionConfig.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void removeDimensionConfigListener(DimensionConfigListener l) {
	Iterator<WeakReference<DimensionConfigListener>> it = listeners.iterator();
	while (it.hasNext()) {
		DimensionConfigListener listener = it.next().get();
		if (listener == null || listener == l) {
			it.remove();
		}
	}
}
 
Example #18
Source File: WindowsPath.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
WindowsPathWithAttributes(WindowsFileSystem fs,
                          WindowsPathType type,
                          String root,
                          String path,
                          BasicFileAttributes attrs)
{
    super(fs, type, root, path);
    ref = new WeakReference<BasicFileAttributes>(attrs);
}
 
Example #19
Source File: BlockMonitor.java    From BlockCanaryEx with Apache License 2.0 5 votes vote down vote up
private static void notifyBlocked(BlockInfo blockInfo) {
    Iterator<WeakReference<BlockObserver>> iterator = sBlockObservers.iterator();
    while (iterator.hasNext()) {
        WeakReference<BlockObserver> observerWeakReference = iterator.next();
        BlockObserver observer = observerWeakReference.get();
        if (observer == null) {
            iterator.remove();
        } else {
            observer.onBlock(blockInfo);
        }
    }
}
 
Example #20
Source File: SubjectDomainCombiner.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public V getValue(K key) {
    WeakReference<V> wr = super.get(key);
    if (wr != null) {
        return wr.get();
    }
    return null;
}
 
Example #21
Source File: Window.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static Window[] getWindows(AppContext appContext) {
    synchronized (Window.class) {
        Window realCopy[];
        @SuppressWarnings("unchecked")
        Vector<WeakReference<Window>> windowList =
            (Vector<WeakReference<Window>>)appContext.get(Window.class);
        if (windowList != null) {
            int fullSize = windowList.size();
            int realSize = 0;
            Window fullCopy[] = new Window[fullSize];
            for (int i = 0; i < fullSize; i++) {
                Window w = windowList.get(i).get();
                if (w != null) {
                    fullCopy[realSize++] = w;
                }
            }
            if (fullSize != realSize) {
                realCopy = Arrays.copyOf(fullCopy, realSize);
            } else {
                realCopy = fullCopy;
            }
        } else {
            realCopy = new Window[0];
        }
        return realCopy;
    }
}
 
Example #22
Source File: PlaceDownloaderTask.java    From android_coursera_1 with MIT License 5 votes vote down vote up
public PlaceDownloaderTask(PlaceViewActivity parent) {
	super();
	mParent = new WeakReference<PlaceViewActivity>(parent);

	if (!HAS_NETWORK) {
		mStubBitmap = BitmapFactory.decodeResource(parent.getResources(),
				R.drawable.stub);
		mockLoc1.setLatitude(37.422);
		mockLoc1.setLongitude(-122.084);
		mockLoc2.setLatitude(38.996667);
		mockLoc2.setLongitude(-76.9275);
	}
}
 
Example #23
Source File: BottomNavigationViewInner.java    From BottomNavigationViewEx with MIT License 5 votes vote down vote up
MyOnNavigationItemSelectedListener(ViewPager viewPager, BottomNavigationViewInner bnve, boolean smoothScroll, OnNavigationItemSelectedListener listener) {
    this.viewPagerRef = new WeakReference<>(viewPager);
    this.listener = listener;
    this.smoothScroll = smoothScroll;

    // create items
    Menu menu = bnve.getMenu();
    int size = menu.size();
    items = new SparseIntArray(size);
    for (int i = 0; i < size; i++) {
        int itemId = menu.getItem(i).getItemId();
        items.put(itemId, i);
    }
}
 
Example #24
Source File: AbstractImageBridge.java    From CrossMobile with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void recycle() {
    active.clear();
    List<WeakReference<CGImage>> next = new ArrayList<>();
    for (WeakReference<CGImage> item : pool) {
        CGImage cur = item.get();
        if (cur != null) {
            trashCGImageMemory(cur);
            next.add(item);
        }
    }
    pool = next;
}
 
Example #25
Source File: WappalyzerJsonParser.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private static Graphics2D addRenderingHints(BufferedImage image) {
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(
            RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, new WeakReference<BufferedImage>(image));
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHint(
            RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    g2d.setRenderingHint(
            RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    return g2d;
}
 
Example #26
Source File: WeakSetTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * test for issue #106218
 * @throws java.lang.Exception
 */
@RandomlyFails // OOME in NB-Core-Build #1908
public void testWeakSetIntegrity() throws Exception {
    //CharSequence log = Log.enable(WeakSet.class.getName(), Level.FINE);
    ArrayList<WeakReference<TestObj>> awr = new ArrayList<WeakReference<TestObj>>();
    ExecutorService exec = Executors.newFixedThreadPool(5);
    exec.execute(new GC());
    for (int i = 0; i < 1000; i++) {
        TestObj to = new TestObj("T" + i);
        awr.add(new WeakReference<TestObj>(to));
        Thread.yield();
        for (WeakReference<TestObj> wro : awr) {
            TestObj wroo = wro.get();
            if (wroo != null) {
                synchronized (TestObj.testObjs) {
                    boolean found = false;
                    for (TestObj o : TestObj.testObjs) {
                        if (o == wroo) {
                            found = true;
                        }
                    }
                    if (found != TestObj.testObjs.contains(wroo)) {
                        //System.out.println(log.toString());
                        fail("Inconsistency of iterator chain and hash map");
                    }
                }
            }
        }
    }
    exec.shutdownNow();
}
 
Example #27
Source File: MyFansAdapter.java    From tysq-android with GNU General Public License v3.0 5 votes vote down vote up
public MyFansAdapter(BitBaseFragment fragment,
                     Context context,
                     TitleCountVO header,
                     List<MyFansListResp.AttentionInfoBean> attentionInfoBeans,
                     MyFansAttentionClickListener listener,
                     boolean isNeedHeader) {
    super(context, header, attentionInfoBeans, isNeedHeader);
    this.mListener = listener;
    this.mFragment = new WeakReference<>(fragment);
}
 
Example #28
Source File: ConfigManage.java    From QSVideoPlayer with Apache License 2.0 5 votes vote down vote up
public static void releaseOther(QSVideoView qs) {
    for (WeakReference<QSVideoView> w : videos) {
        QSVideoView q = w.get();
        if (q != null & q != qs)
            q.release();
    }
}
 
Example #29
Source File: TakeSnapshotProfilingPoint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Report getReport(boolean create) {
    Report report = reportReference == null ? null : reportReference.get();
    if (report == null && create) {
        report = new Report();
        reportReference = new WeakReference<Report>(report);
    }
    return report;
}
 
Example #30
Source File: FragmentStatePagerItemAdapter.java    From SmartTablayout with Apache License 2.0 5 votes vote down vote up
@Override
public Object instantiateItem(ViewGroup container, int position) {
  Object item = super.instantiateItem(container, position);
  if (item instanceof Fragment) {
    holder.put(position, new WeakReference<Fragment>((Fragment) item));
  }
  return item;
}