Java Code Examples for java.util.WeakHashMap

The following examples show how to use java.util.WeakHashMap. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: hadoop-ozone   Source File: ThrottledAsyncChecker.java    License: Apache License 2.0 6 votes vote down vote up
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;
  }
}
 
Example 2
Source Project: dragonwell8_jdk   Source File: TCPTransport.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source Project: netbeans   Source File: TaskSchedulingManager.java    License: Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    });
}
 
Example 4
Source Project: jdk8u-jdk   Source File: TCPTransport.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Source Project: HotswapAgent   Source File: Jersey1Plugin.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source Project: DoraemonKit   Source File: Dispatcher.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 7
Source Project: cache2k   Source File: Cache2kCoreProviderImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
  }
}
 
Example 8
Source Project: onetwo   Source File: SimpleCacheFacadeImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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;
	}
 
Example 9
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;
        }
    };
}
 
Example 10
Source Project: openjdk-jdk8u   Source File: Defaults.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @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)});
}
 
Example 11
Source Project: Stringlate   Source File: ImageLoader.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 12
@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)));
}
 
Example 13
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();
}
 
Example 14
Source Project: coming   Source File: not_covered_not_covered_s.java    License: MIT License 5 votes vote down vote up
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);
}
 
Example 15
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);
	}
}
 
Example 16
Source Project: openjdk-jdk8u   Source File: StyleContext.java    License: GNU General Public License v2.0 5 votes vote down vote up
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();
}
 
Example 17
Source Project: Aria   Source File: CrashHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 发送异常数据给服务器
 */
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);
}
 
Example 18
Source Project: jdk8u-jdk   Source File: Defaults.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @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)});
}
 
Example 19
/**
 * 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);
}
 
Example 20
Source Project: j2objc   Source File: RetainedWithTest.java    License: Apache License 2.0 5 votes vote down vote up
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<>();
    }
  });
}
 
Example 21
Source Project: gemfirexd-oss   Source File: DLockToken.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 22
Source Project: openjdk-8   Source File: RMIConnector.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void initTransients() {
    rmbscMap = new WeakHashMap<Subject, WeakReference<MBeanServerConnection>>();
    connected = false;
    terminated = false;

    connectionBroadcaster = new NotificationBroadcasterSupport();
}
 
Example 23
/**
 * 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()));
            }
        }
    }
}
 
Example 24
Source Project: letv   Source File: ViewPropertyAnimatorCompat.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 25
private void initTransients() {
    rmbscMap = new WeakHashMap<Subject, WeakReference<MBeanServerConnection>>();
    connected = false;
    terminated = false;

    connectionBroadcaster = new NotificationBroadcasterSupport();
}
 
Example 26
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;
}
 
Example 27
Source Project: netbeans   Source File: TimesCollectorPeer.java    License: Apache License 2.0 5 votes vote down vote up
/** Creates a new instance of TimesCollectorPeer */
private TimesCollectorPeer() {
    files = new ArrayList<Reference<Object>>();
    fo2Key2Desc = new WeakHashMap<Object, Map<String, Description>>();
    
    pcs = new PropertyChangeSupport(this);
}
 
Example 28
Source Project: hottub   Source File: TCPChannel.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 29
Source Project: stendhal   Source File: RPEntity.java    License: GNU General Public License v2.0 5 votes vote down vote up
public RPEntity() {
	super();
	attackSources = new ArrayList<>();
	damageReceived = new CounterMap<>(true);
	enemiesThatGiveFightXP = new WeakHashMap<>();
	totalDamageReceived = 0;
	ignoreCollision = false;
}
 
Example 30
Source Project: kyoko   Source File: SnipeCommand.java    License: MIT License 5 votes vote down vote up
@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));
}
 
Example 31
Source Project: TencentKona-8   Source File: PropertyMap.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add a map to the prototype history.
 *
 * @param newProto Prototype to add (key.)
 * @param newMap   {@link PropertyMap} associated with prototype.
 */
private void addToProtoHistory(final ScriptObject newProto, final PropertyMap newMap) {
    if (protoHistory == null) {
        protoHistory = new WeakHashMap<>();
    }

    protoHistory.put(newProto, new SoftReference<>(newMap));
}
 
Example 32
Source Project: openjdk-jdk8u   Source File: ORBImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public synchronized void setTypeCodeForClass(Class c, TypeCodeImpl tci)
{
    checkShutdownState();

    if (typeCodeForClassMap == null)
        typeCodeForClassMap = Collections.synchronizedMap(
            new WeakHashMap(64));
    // Store only one TypeCode per class.
    if ( ! typeCodeForClassMap.containsKey(c))
        typeCodeForClassMap.put(c, tci);
}
 
Example 33
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;
        }
    };
}
 
Example 34
/**
 *
 * @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)});
}
 
Example 35
Source Project: chart-fx   Source File: DefaultFormatter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts the object provided into its string form. Format of the returned string is defined by this converter.
 *
 * @return a string representation of the object passed in.
 * @see StringConverter#toString
 */
@Override
public String toString(final Number object) {
    // TODO: just for testing need to clean-up w.r.t. use of cache etc.
    // return labelCache.get(formatter, object.doubleValue());
    // return labelCache.get(formatter, object.doubleValue());

    if (isExponentialForm) {
        return labelCache.get(myFormatter, object.doubleValue());
    }
    final WeakHashMap<Number, String> hash = numberFormatCache.get(formatterPattern.hashCode());
    if (hash != null) {
        final String label = hash.get(object);
        if (label != null) {
            return label;
        }
    }
    // couldn't find label in cache
    final String retVal = String.format(formatterPattern, object.doubleValue());
    // add retVal to cache
    if (hash == null) {
        final WeakHashMap<Number, String> temp = new WeakHashMap<>();
        temp.put(object, retVal);
        numberFormatCache.put(Integer.valueOf(formatterPattern.hashCode()), temp);
        // checkCache = new WeakHashMap<>();
    } else {
        hash.put(object, retVal);
    }

    return retVal;
}
 
Example 36
Source Project: jdk8u-jdk   Source File: WObjectPeer.java    License: GNU General Public License v2.0 5 votes vote down vote up
final void addChildPeer(WObjectPeer child) {
    synchronized (getStateLock()) {
        if (childPeers == null) {
            childPeers = new WeakHashMap<>();
        }
        if (isDisposed()) {
            throw new IllegalStateException("Parent peer is disposed");
        }
        childPeers.put(child, this);
    }
}
 
Example 37
Source Project: groovy   Source File: TemplateServlet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create new TemplateServlet.
 */
public TemplateServlet() {
    this.cache = new WeakHashMap<String, TemplateCacheEntry>();
    this.engine = null; // assigned later by init()
    this.generateBy = true; // may be changed by init()
    this.fileEncodingParamVal = null; // may be changed by init()
}
 
Example 38
Source Project: chart-fx   Source File: ArrayCache.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns cached large recurring primitive arrays, e.g. to be used in functions where often large temporary arrays
 * are needed but that are otherwise outside the function scope not needed.
 * 
 * <p>
 * N.B. do not forget to release/return ownership of the array via {@link #release}
 * 
 * @param arrayName unique array name
 * @param size requested array size
 * @return cached copy (N.B. removed from internal HashMap)
 */
public static float[] getCachedFloatArray(final String arrayName, final int size) {
    synchronized (floatArrayCache) {
        final WeakHashMap<Integer, float[]> nameHashMap = floatArrayCache.computeIfAbsent(arrayName,
                key -> new WeakHashMap<>());
        float[] cachedArray = nameHashMap.get(size);
        if (cachedArray == null) {
            cachedArray = new float[size];
        } else {
            floatArrayCache.get(arrayName).remove(size);
        }
        return cachedArray;
    }
}
 
Example 39
Source Project: es6draft   Source File: WeakMapPrototype.java    License: MIT License 5 votes vote down vote up
/**
 * 23.3.3.3 WeakMap.prototype.get ( key )
 * 
 * @param cx
 *            the execution context
 * @param thisValue
 *            the function this-value
 * @param key
 *            the key
 * @return the mapped value or undefined
 */
@Function(name = "get", arity = 1)
public static Object get(ExecutionContext cx, Object thisValue, Object key) {
    /* steps 1-3 */
    WeakMapObject m = thisWeakMapObject(cx, thisValue, "WeakMap.prototype.get");
    /* step 4 */
    WeakHashMap<ScriptObject, Object> entries = m.getWeakMapData();
    /* step 5 */
    if (!Type.isObject(key)) {
        return UNDEFINED;
    }
    /* steps 6-7 */
    Object value = entries.get(key);
    return value != null ? value : UNDEFINED;
}
 
Example 40
/**
 * 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()));
            }
        }
    }
}