类java.util.WeakHashMap源码实例Demo

下面列出了怎么用java.util.WeakHashMap的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: hadoop-ozone   文件: ThrottledAsyncChecker.java
public ThrottledAsyncChecker(final Timer timer,
                             final long minMsBetweenChecks,
                             final long diskCheckTimeout,
                             final ExecutorService executorService) {
  this.timer = timer;
  this.minMsBetweenChecks = minMsBetweenChecks;
  this.diskCheckTimeout = diskCheckTimeout;
  this.executorService = MoreExecutors.listeningDecorator(executorService);
  this.checksInProgress = new HashMap<>();
  this.completedChecks = new WeakHashMap<>();

  if (this.diskCheckTimeout > 0) {
    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new
        ScheduledThreadPoolExecutor(1);
    this.scheduledExecutorService = MoreExecutors
        .getExitingScheduledExecutorService(scheduledThreadPoolExecutor);
  } else {
    this.scheduledExecutorService = null;
  }
}
 
源代码2 项目: dragonwell8_jdk   文件: TCPTransport.java
/**
 * Verify that the given AccessControlContext has permission to
 * accept this connection.
 */
void checkAcceptPermission(SecurityManager sm,
                           AccessControlContext acc)
{
    /*
     * Note: no need to synchronize on cache-related fields, since this
     * method only gets called from the ConnectionHandler's thread.
     */
    if (sm != cacheSecurityManager) {
        okContext = null;
        authCache = new WeakHashMap<AccessControlContext,
                                    Reference<AccessControlContext>>();
        cacheSecurityManager = sm;
    }
    if (acc.equals(okContext) || authCache.containsKey(acc)) {
        return;
    }
    InetAddress addr = socket.getInetAddress();
    String host = (addr != null) ? addr.getHostAddress() : "*";

    sm.checkAccept(host, socket.getPort());

    authCache.put(acc, new SoftReference<AccessControlContext>(acc));
    okContext = acc;
}
 
源代码3 项目: netbeans   文件: TaskSchedulingManager.java
private TaskSchedulingManager() {
    support = new PropertyChangeSupport(this);
    initializedRepositories = Collections.synchronizedSet(new HashSet<String>());
    scheduledTasks = Collections.synchronizedMap(new WeakHashMap<IssueImpl, IssueScheduleInfo>());
    persistedTasks = new HashMap<String, Set<String>>();
    issuesToHandle = new LinkedHashSet<IssueImpl>();
    deletedIssues = new LinkedHashSet<IssueImpl>();
    handleTask = RP.create(new HandleTask());
    loadTasks();
    RepositoryRegistry.getInstance().addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (RepositoryRegistry.EVENT_REPOSITORIES_CHANGED.equals(evt.getPropertyName())) {
                repositoriesChanged(evt);
            }
        }
    });
}
 
源代码4 项目: jdk8u-jdk   文件: TCPTransport.java
/**
 * Verify that the given AccessControlContext has permission to
 * accept this connection.
 */
void checkAcceptPermission(SecurityManager sm,
                           AccessControlContext acc)
{
    /*
     * Note: no need to synchronize on cache-related fields, since this
     * method only gets called from the ConnectionHandler's thread.
     */
    if (sm != cacheSecurityManager) {
        okContext = null;
        authCache = new WeakHashMap<AccessControlContext,
                                    Reference<AccessControlContext>>();
        cacheSecurityManager = sm;
    }
    if (acc.equals(okContext) || authCache.containsKey(acc)) {
        return;
    }
    InetAddress addr = socket.getInetAddress();
    String host = (addr != null) ? addr.getHostAddress() : "*";

    sm.checkAccept(host, socket.getPort());

    authCache.put(acc, new SoftReference<AccessControlContext>(acc));
    okContext = acc;
}
 
源代码5 项目: HotswapAgent   文件: Jersey1Plugin.java
/**
 * Gets a list of classes used in configure the Jersey Application
 */
private Set<Class<?>> getContainerClasses(Class<?> resourceConfigClass, Object resourceConfig)
            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {

    Set<Class<?>> containerClasses = Collections.newSetFromMap(new WeakHashMap<Class<?>, Boolean>());

    Set<Class<?>> providerClasses = (Set<Class<?>>) ReflectionHelper.invoke(resourceConfig, resourceConfigClass, "getProviderClasses",  new Class[]{});
    if (providerClasses != null) {
        containerClasses.addAll(providerClasses);
    }

    Set<Class<?>> rootResourceClasses = (Set<Class<?>>) ReflectionHelper.invoke(resourceConfig, resourceConfigClass, "getRootResourceClasses",  new Class[]{});
    if (rootResourceClasses != null) {
        containerClasses.addAll(rootResourceClasses);
    }

    return containerClasses;
}
 
源代码6 项目: DoraemonKit   文件: Dispatcher.java
Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler,
    Downloader downloader, Cache cache, Stats stats) {
  this.dispatcherThread = new DispatcherThread();
  this.dispatcherThread.start();
  Utils.flushStackLocalLeaks(dispatcherThread.getLooper());
  this.context = context;
  this.service = service;
  this.hunterMap = new LinkedHashMap<String, BitmapHunter>();
  this.failedActions = new WeakHashMap<Object, Action>();
  this.pausedActions = new WeakHashMap<Object, Action>();
  this.pausedTags = new HashSet<Object>();
  this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);
  this.downloader = downloader;
  this.mainThreadHandler = mainThreadHandler;
  this.cache = cache;
  this.stats = stats;
  this.batch = new ArrayList<BitmapHunter>(4);
  this.airplaneMode = Utils.isAirplaneModeOn(this.context);
  this.scansNetworkChanges = hasPermission(context, Manifest.permission.ACCESS_NETWORK_STATE);
  this.receiver = new NetworkBroadcastReceiver(this);
  receiver.register();
}
 
源代码7 项目: cache2k   文件: Cache2kCoreProviderImpl.java
/**
 * Called from the manager after a close. Removes the manager from the known managers.
 */
void removeManager(CacheManager cm) {
  synchronized (getLockObject()) {
    Map<String, CacheManager> _name2managers = loader2name2manager.get(cm.getClassLoader());
    _name2managers = new HashMap<String, CacheManager>(_name2managers);
    Object _removed = _name2managers.remove(cm.getName());
    Map<ClassLoader, Map<String, CacheManager>> _copy = new WeakHashMap<ClassLoader, Map<String, CacheManager>>(loader2name2manager);
    _copy.put(cm.getClassLoader(), _name2managers);
    loader2name2manager = _copy;
    if (cm.isDefaultManager()) {
      Map<ClassLoader, String> _defaultNameCopy = new WeakHashMap<ClassLoader, String>(loader2defaultName);
      _defaultNameCopy.remove(cm.getClassLoader());
      loader2defaultName = _defaultNameCopy;
    }
  }
}
 
源代码8 项目: onetwo   文件: SimpleCacheFacadeImpl.java
@Override
	protected Collection<CacheAdapter> loadCaches() {
		if(groups==null){
			groups = new HashSet<String>();
			groups.add(CacheUtils.DEFAULT_CACHE_GROUP);
		}
		Collection<CacheAdapter> caches = new HashSet<CacheAdapter>();
		
//		MapCacheAdapter testCache = new MapCacheAdapter(CacheUtils.DEFAULT_CACHE_GROUP);
		
		for(String group : groups){
			MapCacheAdapter testCache = new MapCacheAdapter(group, new WeakHashMap<Serializable, CacheElement>());
			caches.add(testCache);
		}
		
		return caches;
	}
 
源代码9 项目: hottub   文件: RemoteObjectInvocationHandler.java
protected Map<Method,Long> computeValue(Class<?> remoteClass) {
    return new WeakHashMap<Method,Long>() {
        public synchronized Long get(Object key) {
            Long hash = super.get(key);
            if (hash == null) {
                Method method = (Method) key;
                hash = Util.computeMethodHash(method);
                put(method, hash);
            }
            return hash;
        }
    };
}
 
源代码10 项目: openjdk-jdk8u   文件: Defaults.java
/**
 *
 * @param nullKeys include null keys
 * @param nullValues include null values
 * @return
 */
private static Collection<Object[]> makeRWMaps(boolean nullKeys, boolean nullValues) {
    return Arrays.asList(
        new Object[]{"HashMap", makeMap(HashMap::new, nullKeys, nullValues)},
        new Object[]{"IdentityHashMap", makeMap(IdentityHashMap::new, nullKeys, nullValues)},
        new Object[]{"LinkedHashMap", makeMap(LinkedHashMap::new, nullKeys, nullValues)},
        new Object[]{"WeakHashMap", makeMap(WeakHashMap::new, nullKeys, nullValues)},
        new Object[]{"Collections.checkedMap(HashMap)", Collections.checkedMap(makeMap(HashMap::new, nullKeys, nullValues), IntegerEnum.class, String.class)},
        new Object[]{"Collections.synchronizedMap(HashMap)", Collections.synchronizedMap(makeMap(HashMap::new, nullKeys, nullValues))},
        new Object[]{"ExtendsAbstractMap", makeMap(ExtendsAbstractMap::new, nullKeys, nullValues)});
}
 
源代码11 项目: Stringlate   文件: ImageLoader.java
public ImageLoader(Context context, boolean allowInternetDownload) {
    mContext = context;

    mMemoryCache = new MemoryCache();
    mFileCache = new FileCache(context, "icons");
    mImageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());

    mExecutorService = Executors.newFixedThreadPool(MAX_THREADS);
    mHandler = new Handler();

    mAllowInternetDownload = allowInternetDownload;
}
 
@Test
@Ignore("Intended for use during development only")
public void shouldBeFasterThanSynchronizedMap() throws InterruptedException {
	Map<Integer, WeakReference<String>> synchronizedMap = Collections.synchronizedMap(new WeakHashMap<Integer, WeakReference<String>>());
	StopWatch mapTime = timeMultiThreaded("SynchronizedMap", synchronizedMap, v -> new WeakReference<>(String.valueOf(v)));
	System.out.println(mapTime.prettyPrint());

	this.map.setDisableTestHooks(true);
	StopWatch cacheTime = timeMultiThreaded("WeakConcurrentCache", this.map, String::valueOf);
	System.out.println(cacheTime.prettyPrint());

	// We should be at least 4 time faster
	assertThat(cacheTime.getTotalTimeSeconds(), is(lessThan(mapTime.getTotalTimeSeconds() / 4.0)));
}
 
源代码13 项目: openjdk-jdk8u-backup   文件: StyleContext.java
private void readObject(ObjectInputStream s)
  throws ClassNotFoundException, IOException
{
    fontSearch = new FontKey(null, 0, 0);
    fontTable = new Hashtable<FontKey, Font>();
    search = new SimpleAttributeSet();
    attributesPool = Collections.
            synchronizedMap(new WeakHashMap<SmallAttributeSet, WeakReference<SmallAttributeSet>>());
    s.defaultReadObject();
}
 
源代码14 项目: coming   文件: not_covered_not_covered_s.java
public void invalidate() {
    if (mNativeMap.isEmpty()) { return; }

    final WeakHashMap<android.view.MenuItem, MenuItem> menuMapCopy = new WeakHashMap<android.view.MenuItem, MenuItem>(mNativeMap.size());

    for (int i = 0; i < mNativeMenu.size(); i++) {
      final android.view.MenuItem item = mNativeMenu.getItem(i);
      menuMapCopy.put(item, mNativeMap.get(item));
    }

    mNativeMap.clear();
    mNativeMap.putAll(menuMapCopy);
}
 
private void addActiveNewCardsView(final int boardId, final IView view)
{
	final Set<IView> boardActiveViews = boardId2newCardsViewId.computeIfAbsent(boardId, id -> Collections.newSetFromMap(new WeakHashMap<>()));
	synchronized (boardActiveViews)
	{
		boardActiveViews.add(view);
	}
}
 
源代码16 项目: openjdk-jdk8u   文件: StyleContext.java
private void readObject(ObjectInputStream s)
  throws ClassNotFoundException, IOException
{
    fontSearch = new FontKey(null, 0, 0);
    fontTable = new Hashtable<FontKey, Font>();
    search = new SimpleAttributeSet();
    attributesPool = Collections.
            synchronizedMap(new WeakHashMap<SmallAttributeSet, WeakReference<SmallAttributeSet>>());
    s.defaultReadObject();
}
 
源代码17 项目: Aria   文件: CrashHandler.java
/**
 * 发送异常数据给服务器
 */
private void sendExceptionInfo(final Throwable ex) {
  ExceptionInfo info = new ExceptionInfo();
  info.time = CalendarUtils.getNowDataTime();
  info.versionCode = AndroidUtils.getVersionCode(mContext);
  info.versionName = AndroidUtils.getVersionName(mContext);
  info.systemVersionCode = Build.VERSION.SDK_INT;
  info.phoneModel = Build.MODEL;
  info.exceptionMsg = FL.getExceptionString(ex);
  if (AndroidUtils.checkPermission(mContext, Manifest.permission.INTERNET) &&
      AndroidUtils.checkPermission(mContext, Manifest.permission.ACCESS_NETWORK_STATE)) {
    if (NetUtils.isConnected(mContext) && !TextUtils.isEmpty(mServerHost) && !TextUtils.isEmpty(
        mPramKey)) {
      String objStr = new Gson().toJson(info);
      HttpUtil util = HttpUtil.getInstance(mContext);
      Map<String, String> params = new WeakHashMap<>();
      params.put(mPramKey, objStr);
      util.get(mServerHost, params, new HttpUtil.AbsResponse());
    }
  } else {
    L.e(TAG,
        "请在manifest文件定义android.permission.INTERNET和android.permission.ACCESS_NETWORK_STATE权限");
    return;
  }
  File file = new File(mContext.getCacheDir().getPath() + "/crash/" + mExceptionFileName);
  if (!file.exists()) {
    FileUtil.createFile(file.getPath());
  }
  writeExceptionToFile(info.exceptionMsg, file);
}
 
源代码18 项目: jdk8u-jdk   文件: Defaults.java
/**
 *
 * @param nullKeys include null keys
 * @param nullValues include null values
 * @return
 */
private static Collection<Object[]> makeRWMaps(boolean nullKeys, boolean nullValues) {
    return Arrays.asList(
        new Object[]{"HashMap", makeMap(HashMap::new, nullKeys, nullValues)},
        new Object[]{"IdentityHashMap", makeMap(IdentityHashMap::new, nullKeys, nullValues)},
        new Object[]{"LinkedHashMap", makeMap(LinkedHashMap::new, nullKeys, nullValues)},
        new Object[]{"WeakHashMap", makeMap(WeakHashMap::new, nullKeys, nullValues)},
        new Object[]{"Collections.checkedMap(HashMap)", Collections.checkedMap(makeMap(HashMap::new, nullKeys, nullValues), IntegerEnum.class, String.class)},
        new Object[]{"Collections.synchronizedMap(HashMap)", Collections.synchronizedMap(makeMap(HashMap::new, nullKeys, nullValues))},
        new Object[]{"ExtendsAbstractMap", makeMap(ExtendsAbstractMap::new, nullKeys, nullValues)});
}
 
源代码19 项目: openjdk-8   文件: PropertyListenerManager.java
/**
 * Add a property listener to this object.
 *
 * @param listener The property listener that is added.
 */
public synchronized final void addPropertyListener(final PropertyListener listener) {
    if (listeners == null) {
        listeners = new WeakHashMap<>();
    }

    if (Context.DEBUG) {
        listenersAdded++;
    }
    listeners.put(listener, Boolean.TRUE);
}
 
源代码20 项目: j2objc   文件: RetainedWithTest.java
public void testMapChildren() {
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new IdentityHashMap<>();
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new WeakHashMap<>();
    }
  });
  new MapTest<Color>().run(new MapFactory<Color>(Color.RED) {
    public Map<Color, ValueType> newMap() {
      return new EnumMap<>(Color.class);
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new HashMap<>();
    }
  });
  new MapTest<Integer>().run(new MapFactory<Integer>(5) {
    public Map<Integer, ValueType> newMap() {
      return new TreeMap<>();
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new Hashtable<>();
    }
  });
  new MapTest<>().run(new MapFactory<Object>(new Object()) {
    public Map<Object, ValueType> newMap() {
      return new ConcurrentHashMap<>();
    }
  });
}
 
源代码21 项目: gemfirexd-oss   文件: DLockToken.java
/**
 * Record the token's owning thread as having lost its lease, so it can 
 * throw an exception later if it tries to unlock. A weak reference to the 
 * thread is used. Caller must synchronize on this lock token.
 */
private void noteExpiredLease() {
  if (this.log.fineEnabled()) {
    this.log.fine("[noteExpiredLease] " + this.thread);
  }
  if (this.expiredLeases == null) {
    this.expiredLeases = new WeakHashMap();
  }
  this.expiredLeases.put(this.thread, null);
}
 
源代码22 项目: openjdk-8   文件: RMIConnector.java
private void initTransients() {
    rmbscMap = new WeakHashMap<Subject, WeakReference<MBeanServerConnection>>();
    connected = false;
    terminated = false;

    connectionBroadcaster = new NotificationBroadcasterSupport();
}
 
源代码23 项目: openjdk-jdk8u   文件: PropertyListeners.java
/**
 * Copy constructor
 * @param listener listener to copy
 */
PropertyListeners(final PropertyListeners listener) {
    if (listener != null && listener.listeners != null) {
        this.listeners = new WeakHashMap<>();
        // We need to copy the nested weak sets in order to avoid concurrent modification issues, see JDK-8146274
        synchronized (listener) {
            for (final Map.Entry<String, WeakPropertyMapSet> entry : listener.listeners.entrySet()) {
                this.listeners.put(entry.getKey(), new WeakPropertyMapSet(entry.getValue()));
            }
        }
    }
}
 
源代码24 项目: letv   文件: ViewPropertyAnimatorCompat.java
private void postStartMessage(ViewPropertyAnimatorCompat vpa, View view) {
    Runnable runnable = null;
    if (this.mStarterMap != null) {
        runnable = (Runnable) this.mStarterMap.get(view);
    }
    if (runnable == null) {
        runnable = new Starter(vpa, view);
        if (this.mStarterMap == null) {
            this.mStarterMap = new WeakHashMap();
        }
        this.mStarterMap.put(view, runnable);
    }
    view.removeCallbacks(runnable);
    view.post(runnable);
}
 
源代码25 项目: openjdk-8-source   文件: RMIConnector.java
private void initTransients() {
    rmbscMap = new WeakHashMap<Subject, WeakReference<MBeanServerConnection>>();
    connected = false;
    terminated = false;

    connectionBroadcaster = new NotificationBroadcasterSupport();
}
 
源代码26 项目: tracee   文件: BackendProviderResolver.java
private void updatedCache(final ClassLoader classLoader, final Set<TraceeBackendProvider> provider) {
	final Map<ClassLoader, Set<TraceeBackendProvider>> copyOnWriteMap = new WeakHashMap<>(providersPerClassloader);
	if (!provider.isEmpty()) {
		copyOnWriteMap.put(classLoader, new BackendProviderSet(provider));
	} else {
		copyOnWriteMap.put(classLoader, new EmptyBackendProviderSet());
	}
	providersPerClassloader = copyOnWriteMap;
}
 
源代码27 项目: netbeans   文件: TimesCollectorPeer.java
/** Creates a new instance of TimesCollectorPeer */
private TimesCollectorPeer() {
    files = new ArrayList<Reference<Object>>();
    fo2Key2Desc = new WeakHashMap<Object, Map<String, Description>>();
    
    pcs = new PropertyChangeSupport(this);
}
 
源代码28 项目: hottub   文件: TCPChannel.java
/**
 * Checks if the current caller has sufficient privilege to make
 * a connection to the remote endpoint.
 * @exception SecurityException if caller is not allowed to use this
 * Channel.
 */
private void checkConnectPermission() throws SecurityException {
    SecurityManager security = System.getSecurityManager();
    if (security == null)
        return;

    if (security != cacheSecurityManager) {
        // The security manager changed: flush the cache
        okContext = null;
        authcache = new WeakHashMap<AccessControlContext,
                                    Reference<AccessControlContext>>();
        cacheSecurityManager = security;
    }

    AccessControlContext ctx = AccessController.getContext();

    // If ctx is the same context as last time, or if it
    // appears in the cache, bypass the checkConnect.
    if (okContext == null ||
        !(okContext.equals(ctx) || authcache.containsKey(ctx)))
    {
        security.checkConnect(ep.getHost(), ep.getPort());
        authcache.put(ctx, new SoftReference<AccessControlContext>(ctx));
        // A WeakHashMap is transformed into a SoftHashSet by making
        // each value softly refer to its own key (Peter's idea).
    }
    okContext = ctx;
}
 
源代码29 项目: stendhal   文件: RPEntity.java
public RPEntity() {
	super();
	attackSources = new ArrayList<>();
	damageReceived = new CounterMap<>(true);
	enemiesThatGiveFightXP = new WeakHashMap<>();
	totalDamageReceived = 0;
	ignoreCollision = false;
}
 
源代码30 项目: kyoko   文件: SnipeCommand.java
@Override
public void onRegister() {
    messageCache = Caffeine.newBuilder().maximumSize(150).softValues().build();
    snipes = new WeakHashMap<>();
    consumers.add(eventManager.registerEventHandler(DiscordEvent.MESSAGE_CREATE, this::onMessage));
    consumers.add(eventManager.registerEventHandler(DiscordEvent.MESSAGE_DELETE, this::onDelete));
    consumers.add(eventManager.registerEventHandler(DiscordEvent.MESSAGE_UPDATE, this::onEdit));
}
 
 类所在包
 同包方法