下面列出了java.util.AbstractSet#java.util.WeakHashMap 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
}
/**
* 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;
}
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);
}
}
});
}
/**
* 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;
}
/**
* 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;
}
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();
}
/**
* 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;
}
}
}
@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;
}
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;
}
};
}
/**
*
* @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)});
}
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)));
}
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();
}
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);
}
}
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();
}
/**
* 发送异常数据给服务器
*/
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);
}
/**
*
* @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)});
}
/**
* 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);
}
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<>();
}
});
}
/**
* 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);
}
private void initTransients() {
rmbscMap = new WeakHashMap<Subject, WeakReference<MBeanServerConnection>>();
connected = false;
terminated = false;
connectionBroadcaster = new NotificationBroadcasterSupport();
}
/**
* 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()));
}
}
}
}
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);
}
private void initTransients() {
rmbscMap = new WeakHashMap<Subject, WeakReference<MBeanServerConnection>>();
connected = false;
terminated = false;
connectionBroadcaster = new NotificationBroadcasterSupport();
}
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;
}
/** Creates a new instance of TimesCollectorPeer */
private TimesCollectorPeer() {
files = new ArrayList<Reference<Object>>();
fo2Key2Desc = new WeakHashMap<Object, Map<String, Description>>();
pcs = new PropertyChangeSupport(this);
}
/**
* 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;
}
public RPEntity() {
super();
attackSources = new ArrayList<>();
damageReceived = new CounterMap<>(true);
enemiesThatGiveFightXP = new WeakHashMap<>();
totalDamageReceived = 0;
ignoreCollision = false;
}
@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));
}