Java Code Examples for java.util.WeakHashMap

The following are top voted examples for showing how to use java.util.WeakHashMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Bing   File: DownloadHandler.java   View source code 6 votes vote down vote up
public DownloadHandler(String url,
                       WeakHashMap<String, Object> params,
                       IRequest request,
                       String downDir,
                       String extension,
                       String name,
                       ISuccess success,
                       IFailure failure,
                       IError error) {
    this.URL = url;
    this.PARAMS = params;
    this.REQUEST = request;
    this.DOWNLOAD_DIR = downDir;
    this.EXTENSION = extension;
    this.NAME = name;
    this.SUCCESS = success;
    this.FAILURE = failure;
    this.ERROR = error;
}
 
Example 2
Project: aos-MediaLib   File: ImageViewSetter.java   View source code 6 votes vote down vote up
/**
 * Creates a new instance.
 * @param context
 * @param config - may be null, default will be used
 */
public ImageViewSetter(Context context, ImageViewSetterConfiguration config) {
    mConfig = (config == null) ? ImageViewSetterConfiguration.getDefault() : config;
    mTaskMap = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());

    if (mConfig.interruptThreads) {
        mThreadMap = Collections.synchronizedMap(new WeakHashMap<ImageView, Thread>());
        mThreadLock = new MultiLock<ImageView>();
    } else {
        mThreadMap = null;
        mThreadLock = null;
    }

    mHandler = new Handler(context.getMainLooper(), new ForegroundHandler());
    mCache = mConfig.useCache ?
            new BitmapMemoryCache(mConfig.cacheSize) : null;

    mDefaultDrawable = mConfig.whileLoading;
}
 
Example 3
Project: incubator-netbeans   File: ClassLoaderManager.java   View source code 6 votes vote down vote up
static void initialize(ProfilerServer inProfilerServer) {
    try {
        Class classLoaderClass = ClassLoader.class;
        Class[] stringArg = new Class[] { String.class };
        findLoadedClassMethod = classLoaderClass.getDeclaredMethod("findLoadedClass", stringArg); // NOI18N
        findLoadedClassMethod.setAccessible(true); // REQUIRED to suppress
        findBootstrapClassMethod = classLoaderClass.getDeclaredMethod("findBootstrapClass", stringArg); // NOI18N
        findBootstrapClassMethod.setAccessible(true); // access checks
    } catch (Exception ex) {
        System.err.println(ENGINE_WARNING+"Cannot use ClassLoader.findLoadedClass() and/or ClassLoader.findBootstrapClass() in ClassLoaderManager"); // NOI18N
        if (DEBUG) ex.printStackTrace(System.err);
        findLoadedClassMethod = null;
        findBootstrapClassMethod = null;          
    }

    // This is done to just initialize some reflection classes, which may otherwise be initialized only when
    // this class is used for the first time, and thus may cause endless class load recursion
    ClassLoaderManager clm = new ClassLoaderManager(ClassLoader.getSystemClassLoader(), 0);
    clm.getLoadedClass("java.lang.String"); // NOI18N

    profilerServer = inProfilerServer;

    manMap = new WeakHashMap();
    manVec = new Vector();
    rq = new ReferenceQueue();
}
 
Example 4
Project: YouTube-Thumbnail-View   File: ThumbnailLoader.java   View source code 6 votes vote down vote up
private ThumbnailLoader(@Nullable Context context, @Nullable String googleApiKey) {
   String metaGoogleApiKey = googleApiKey;
   if (context != null) {
      try {
         final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
         if (appInfo.metaData != null) {
            metaGoogleApiKey = appInfo.metaData.getString("com.codewaves.youtubethumbnailview.ApiKey");
         }
      }
      catch (PackageManager.NameNotFoundException e) {
         // Ignore
      }
   }

   final BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>();
   executor = new ThreadPoolExecutor(DEFAULT_THREAD_POOL_SIZE, DEFAULT_THREAD_POOL_SIZE, 0L, TimeUnit.MILLISECONDS, taskQueue);

   requestMap = new WeakHashMap<>();
   defaultInfoDownloader = new ApiVideoInfoDownloader(metaGoogleApiKey);
   defaultImageLoader = new SimpleImageLoader();
}
 
Example 5
Project: openjdk-jdk10   File: StyleContext.java   View source code 6 votes vote down vote up
private void readObject(ObjectInputStream s)
  throws ClassNotFoundException, IOException
{
    fontSearch = new FontKey(null, 0, 0);
    fontTable = new Hashtable<>();
    search = new SimpleAttributeSet();
    attributesPool = Collections.
            synchronizedMap(new WeakHashMap<SmallAttributeSet,
                    WeakReference<SmallAttributeSet>>());

    ObjectInputStream.GetField f = s.readFields();
    Style newStyles = (Style) f.get("styles", null);
    if (newStyles == null) {
        throw new InvalidObjectException("Null styles");
    }
    styles = newStyles;
    unusedSets = f.get("unusedSets", 0);
}
 
Example 6
Project: ThinkingInJavaStudy   File: Test.java   View source code 6 votes vote down vote up
public static void main(String[] strs) {
    int size = 100;
    Key[] a = new Key[100];
    WeakHashMap<Key, Value> weakHashMap = new WeakHashMap<>();

    for (int i = 0; i < size; i++) {
        Key key = new Key(i+"");
        Value value = new Value(i + "");
        if (i % 3 == 0) {
            a[i] = key;
        }
        weakHashMap.put(key, value);
    }

    System.gc();

    System.out.println(weakHashMap);
}
 
Example 7
Project: OpenJSharp   File: PropertyListeners.java   View source code 6 votes vote down vote up
/**
 * Add a property listener to this object.
 *
 * @param propertyMap The property listener that is added.
 */
synchronized final void addListener(final String key, final PropertyMap propertyMap) {
    if (Context.DEBUG) {
        listenersAdded++;
    }
    if (listeners == null) {
        listeners = new WeakHashMap<>();
    }

    WeakPropertyMapSet set = listeners.get(key);
    if (set == null) {
        set = new WeakPropertyMapSet();
        listeners.put(key, set);
    }
    if (!set.contains(propertyMap)) {
        set.add(propertyMap);
    }
}
 
Example 8
Project: gemini.blueprint   File: WeakCollectionTest.java   View source code 6 votes vote down vote up
public void testWeakHashMap() {
	Map weakMap = new WeakHashMap();

	for (int i = 0; i < 10; i++) {
		weakMap.put(new Object(), null);
	}

	GCTests.assertGCed(new WeakReference(new Object()));

	Set entries = weakMap.entrySet();
	
	for (Iterator iter = entries.iterator(); iter.hasNext();) {
		Map.Entry entry = (Map.Entry) iter.next();
		assertNull(entry.getKey());
	}

}
 
Example 9
Project: OpenJSharp   File: TCPTransport.java   View source code 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 10
Project: datatree   File: Cache.java   View source code 6 votes vote down vote up
public Cache(final int capacity, final boolean fair) {
	ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
	readerLock = lock.readLock();
	writerLock = lock.writeLock();
	weakCache = new WeakHashMap<KEY, VALUE>(capacity);
	hardCache = new LinkedHashMap<KEY, VALUE>(capacity + 1, 1.0f, true) {

		private static final long serialVersionUID = 5994447707758047152L;

		protected final boolean removeEldestEntry(Map.Entry<KEY, VALUE> entry) {
			if (this.size() > capacity) {
				weakCache.put(entry.getKey(), entry.getValue());
				return true;
			}
			return false;
		};
	};
}
 
Example 11
Project: UniversalEventBus   File: RxBus.java   View source code 5 votes vote down vote up
/**
 * With this constructor the {@link RxBus} use a {@link PublishSubject} and instantiate it calling the static method {@code PublishSubject.create()}
 * @see PublishSubject
 */
public RxBus() {
    super((Subject<T, R>) PublishSubject.create());
    mSubscriptionsList = new WeakHashMap<>();
}
 
Example 12
Project: RNLearn_Project1   File: JavaScriptModuleRegistry.java   View source code 5 votes vote down vote up
public JavaScriptModuleRegistry(List<JavaScriptModuleRegistration> config) {
  mModuleInstances = new WeakHashMap<>();
  mModuleRegistrations = new HashMap<>();
  for (JavaScriptModuleRegistration registration : config) {
    mModuleRegistrations.put(registration.getModuleInterface(), registration);
  }
}
 
Example 13
Project: GitHub   File: Picasso.java   View source code 5 votes vote down vote up
Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
    RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers, Stats stats,
    Bitmap.Config defaultBitmapConfig, boolean indicatorsEnabled, boolean loggingEnabled) {
  this.context = context;
  this.dispatcher = dispatcher;
  this.cache = cache;
  this.listener = listener;
  this.requestTransformer = requestTransformer;
  this.defaultBitmapConfig = defaultBitmapConfig;

  int builtInHandlers = 7; // Adjust this as internal handlers are added or removed.
  int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);
  List<RequestHandler> allRequestHandlers = new ArrayList<>(builtInHandlers + extraCount);

  // ResourceRequestHandler needs to be the first in the list to avoid
  // forcing other RequestHandlers to perform null checks on request.uri
  // to cover the (request.resourceId != 0) case.
  allRequestHandlers.add(new ResourceRequestHandler(context));
  if (extraRequestHandlers != null) {
    allRequestHandlers.addAll(extraRequestHandlers);
  }
  allRequestHandlers.add(new ContactsPhotoRequestHandler(context));
  allRequestHandlers.add(new MediaStoreRequestHandler(context));
  allRequestHandlers.add(new ContentStreamRequestHandler(context));
  allRequestHandlers.add(new AssetRequestHandler(context));
  allRequestHandlers.add(new FileRequestHandler(context));
  allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));
  requestHandlers = Collections.unmodifiableList(allRequestHandlers);

  this.stats = stats;
  this.targetToAction = new WeakHashMap<>();
  this.targetToDeferredRequestCreator = new WeakHashMap<>();
  this.indicatorsEnabled = indicatorsEnabled;
  this.loggingEnabled = loggingEnabled;
  this.referenceQueue = new ReferenceQueue<>();
  this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);
  this.cleanupThread.start();
}
 
Example 14
Project: openjdk-jdk10   File: TCPChannel.java   View source code 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 15
Project: incubator-netbeans   File: AttrSet.java   View source code 5 votes vote down vote up
final AttrSet cachedOverride(Object override) {
    AttrSet attrSet;
    if (overrideCache == null) {
        overrideCache = new WeakHashMap<AttrSet,WeakReference<AttrSet>>(4);
        attrSet = null;
    } else {
        WeakReference<AttrSet> ref = (WeakReference<AttrSet>) ((Map<?,?>)overrideCache).get(override);
        attrSet = (ref != null) ? ref.get() : null;
    }
    overrideGets++;
    return attrSet;
}
 
Example 16
Project: data-mediator   File: Binder.java   View source code 5 votes vote down vote up
/**
 * create binder for target data mediator.
 * @param mMediator the target data mediator.
 */
protected Binder(DataMediator<T> mMediator) {
    Throwables.checkNull(mMediator);
    this.mMediator = mMediator;
    this.mMap = shouldUseWeakMap() ? new WeakHashMap<Object, DataMediatorCallback<T>>()
            : new HashMap<Object, DataMediatorCallback<T>>();
}
 
Example 17
Project: monarch   File: Configuration.java   View source code 5 votes vote down vote up
/**
 * Load a class by name, returning null rather than throwing an exception if it couldn't be
 * loaded. This is to avoid the overhead of creating an exception.
 *
 * @param name the class name
 * @return the class object, or null if it could not be found.
 */
public Class<?> getClassByNameOrNull(String name) {
  Map<String, Class<?>> map;

  synchronized (CACHE_CLASSES) {
    map = CACHE_CLASSES.get(classLoader);
    if (map == null) {
      map = Collections.synchronizedMap(new WeakHashMap<String, Class<?>>());
      CACHE_CLASSES.put(classLoader, map);
    }
  }

  Class<?> clazz = map.get(name);
  if (clazz == null) {
    try {
      clazz = Class.forName(name, true, classLoader);
    } catch (ClassNotFoundException e) {
      // Leave a marker that the class isn't found
      map.put(name, NEGATIVE_CACHE_SENTINEL);
      return null;
    }
    // two putters can race here, but they'll put the same class
    map.put(name, clazz);
    return clazz;
  } else if (clazz == NEGATIVE_CACHE_SENTINEL) {
    return null; // not found
  } else {
    // cache hit
    return clazz;
  }
}
 
Example 18
Project: incubator-netbeans   File: LineBreakpoint.java   View source code 5 votes vote down vote up
/**
 * Set the thread filter for a specific debugger session. This restricts
 * the breakpoint to specific threads in that session.
 * @param session the debugger session
 * @param threads the threads or <code>null</code> to unset the filter.
 */
public void setThreadFilters(JPDADebugger session, JPDAThread[] threads) {
    if (threadFilters == null) {
        threadFilters = new WeakHashMap<JPDADebugger, JPDAThread[]>();
    }
    if (threads != null) {
        threadFilters.put(session, threads);
    } else {
        threadFilters.remove(session);
    }
    firePropertyChange(PROP_THREAD_FILTERS, null,
            threads != null ?
                new Object[] { session, threads } : null);
}
 
Example 19
Project: incubator-netbeans   File: MethodBreakpoint.java   View source code 5 votes vote down vote up
/**
 * Set the instance filter for a specific debugger session. This restricts
 * the breakpoint to specific instances in that session.
 * @param session the debugger session
 * @param instances the object instances or <code>null</code> to unset the filter.
 */
public void setInstanceFilters(JPDADebugger session, ObjectVariable[] instances) {
    if (instanceFilters == null) {
        instanceFilters = new WeakHashMap<JPDADebugger, ObjectVariable[]>();
    }
    if (instances != null) {
        instanceFilters.put(session, instances);
    } else {
        instanceFilters.remove(session);
    }
    firePropertyChange(PROP_INSTANCE_FILTERS, null,
            instances != null ?
                new Object[] { session, instances } : null);
}
 
Example 20
Project: incubator-netbeans   File: MethodBreakpoint.java   View source code 5 votes vote down vote up
/**
 * Set the thread filter for a specific debugger session. This restricts
 * the breakpoint to specific threads in that session.
 * @param session the debugger session
 * @param threads the threads or <code>null</code> to unset the filter.
 */
public void setThreadFilters(JPDADebugger session, JPDAThread[] threads) {
    if (threadFilters == null) {
        threadFilters = new WeakHashMap<JPDADebugger, JPDAThread[]>();
    }
    if (threads != null) {
        threadFilters.put(session, threads);
    } else {
        threadFilters.remove(session);
    }
    firePropertyChange(PROP_THREAD_FILTERS, null,
            threads != null ?
                new Object[] { session, threads } : null);
}
 
Example 21
Project: incubator-netbeans   File: TimesCollectorPeer.java   View source code 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 22
Project: incubator-netbeans   File: Manager.java   View source code 5 votes vote down vote up
/**
 */
private void addDisplay(final TestSession session) {
    if (displaysMap == null) {
        displaysMap = new WeakHashMap<TestSession,Boolean>(4);
    }
    displaysMap.put(session, Boolean.TRUE);
}
 
Example 23
Project: incubator-netbeans   File: MylynSupport.java   View source code 5 votes vote down vote up
@NbBundle.Messages({
    "LBL_LocalTaskRepository.displayName=Local Tasks"
})
private MylynSupport () {
    taskRepositoryManager = new TaskRepositoryManager();
    taskRepositoryManager.addRepositoryConnector(new LocalRepositoryConnector());
    localTaskRepository = new TaskRepository(LocalRepositoryConnector.CONNECTOR_KIND, LocalRepositoryConnector.REPOSITORY_URL);
    localTaskRepository.setRepositoryLabel(Bundle.LBL_LocalTaskRepository_displayName());
    taskRepositoryManager.addRepository(localTaskRepository);

    taskList = new TaskList();
    repositoryModel = new RepositoryModel(taskList, taskRepositoryManager);
    synchronizationManager = new SynchronizationManger(repositoryModel);
    taskActivityManager = new TaskActivityManager(taskRepositoryManager, taskList);
    TaskDataStore taskDataStore = new TaskDataStore(taskRepositoryManager);
    taskDataManager = new TaskDataManager(taskDataStore, taskRepositoryManager, taskList,
            taskActivityManager, synchronizationManager);

    String storagePath = Places.getUserDirectory().getAbsolutePath()
            + "/var/tasks/mylyn".replace("/", File.separator); //NOI18N
    taskListStorageFile = new File(storagePath, ITasksCoreConstants.DEFAULT_TASK_LIST_FILE);
    taskDataManager.setDataPath(storagePath);
    taskListWriter = new TaskListExternalizer(repositoryModel, taskRepositoryManager);
    AccessorImpl.getInstance(); // initializes Accessor
    saveTask = RP.create(new Runnable() {
        @Override
        public void run () {
            try {
                persist(false);
            } catch (CoreException ex) {
                LOG.log(Level.WARNING, null, ex);
            }
        }
    });
    unsubmittedTaskContainers = new WeakHashMap<TaskRepository, UnsubmittedTasksContainer>();
    taskDataListeners = new CopyOnWriteArrayList<TaskDataListener>();
    taskListeners = new WeakHashMap<ITask, List<TaskListener>>();
    attachListeners();
}
 
Example 24
Project: OpenJSharp   File: RMIConnector.java   View source code 5 votes vote down vote up
private void initTransients() {
    rmbscMap = new WeakHashMap<Subject, WeakReference<MBeanServerConnection>>();
    connected = false;
    terminated = false;

    connectionBroadcaster = new NotificationBroadcasterSupport();
}
 
Example 25
Project: RNLearn_Project1   File: JavaScriptModuleRegistry.java   View source code 5 votes vote down vote up
public JavaScriptModuleRegistry(List<JavaScriptModuleRegistration> config) {
  mModuleInstances = new WeakHashMap<>();
  mModuleRegistrations = new HashMap<>();
  for (JavaScriptModuleRegistration registration : config) {
    mModuleRegistrations.put(registration.getModuleInterface(), registration);
  }
}
 
Example 26
Project: incubator-netbeans   File: DefaultTopComponentLookup.java   View source code 5 votes vote down vote up
@Override
protected synchronized void beforeLookup(Template<?> t) {
    if ((attachedTo == null) && isNodeQuery(t.getType())) {
        Lookup[] arr = getLookups();

        attachedTo = new WeakHashMap<Lookup,Lookup.Result>(arr.length * 2);

        for (int i = 0; i < (arr.length - 2); i++) {
            Lookup.Result<?> res = arr[i].lookup(t);
            res.addLookupListener(listener);
            attachedTo.put(arr[i], res);
        }
    }
}
 
Example 27
Project: Bing   File: MainActivity.java   View source code 5 votes vote down vote up
public void testRx1(){
    final String url = "about.php";
    final WeakHashMap<String, Object> params = new WeakHashMap<>();
    RestCreator.getRxRestService().get(url,params)
            .compose(this.<String>bindToLifecycle())
            .compose(RxSchedulers.<String>compose())
            .subscribe(new CommonObserver<String>(this) {
                @Override
                public void onNext(@NonNull String s) {
                    Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
                }
            });
}
 
Example 28
Project: openjdk-jdk10   File: PropertyMap.java   View source code 5 votes vote down vote up
/**
 * Track the modification of the map.
 *
 * @param property Mapping property.
 * @param newMap   Modified {@link PropertyMap}.
 */
private void addToHistory(final Property property, final PropertyMap newMap) {
    if (history == null) {
        history = new WeakHashMap<>();
    }

    history.put(property, softReferenceDerivationLimit == 0 ? new WeakReference<>(newMap) : new SoftReference<>(newMap));
}
 
Example 29
Project: rapidminer   File: ProcessRendererModel.java   View source code 5 votes vote down vote up
public ProcessRendererModel() {
	this.eventListener = new EventListenerList();

	this.processes = Collections.unmodifiableList(Collections.<ExecutionUnit> emptyList());
	this.selectedOperators = Collections.unmodifiableList(Collections.<Operator> emptyList());
	this.draggedOperators = Collections.unmodifiableList(Collections.<Operator> emptyList());
	this.processSizes = new WeakHashMap<>();
	this.portNumbers = new WeakHashMap<>();
	this.snapToGrid = Boolean.parseBoolean(ParameterService
			.getParameterValue(RapidMinerGUI.PROPERTY_RAPIDMINER_GUI_SNAP_TO_GRID));
	this.hoveringProcessIndex = -1;

	// listen for snapToGrid changes
	ParameterService.registerParameterChangeListener(new ParameterChangeListener() {

		@Override
		public void informParameterSaved() {
			// ignore
		}

		@Override
		public void informParameterChanged(String key, String value) {
			if (RapidMinerGUI.PROPERTY_RAPIDMINER_GUI_SNAP_TO_GRID.equals(key)) {
				setSnapToGrid(Boolean.parseBoolean(value));
			}
		}
	});
}
 
Example 30
Project: hadoop-oss   File: Configuration.java   View source code 5 votes vote down vote up
/**
 * Load a class by name, returning null rather than throwing an exception
 * if it couldn't be loaded. This is to avoid the overhead of creating
 * an exception.
 * 
 * @param name the class name
 * @return the class object, or null if it could not be found.
 */
public Class<?> getClassByNameOrNull(String name) {
  Map<String, WeakReference<Class<?>>> map;
  
  synchronized (CACHE_CLASSES) {
    map = CACHE_CLASSES.get(classLoader);
    if (map == null) {
      map = Collections.synchronizedMap(
        new WeakHashMap<String, WeakReference<Class<?>>>());
      CACHE_CLASSES.put(classLoader, map);
    }
  }

  Class<?> clazz = null;
  WeakReference<Class<?>> ref = map.get(name); 
  if (ref != null) {
     clazz = ref.get();
  }
   
  if (clazz == null) {
    try {
      clazz = Class.forName(name, true, classLoader);
    } catch (ClassNotFoundException e) {
      // Leave a marker that the class isn't found
      map.put(name, new WeakReference<Class<?>>(NEGATIVE_CACHE_SENTINEL));
      return null;
    }
    // two putters can race here, but they'll put the same class
    map.put(name, new WeakReference<Class<?>>(clazz));
    return clazz;
  } else if (clazz == NEGATIVE_CACHE_SENTINEL) {
    return null; // not found
  } else {
    // cache hit
    return clazz;
  }
}
 
Example 31
Project: openjdk-jdk10   File: SunToolkit.java   View source code 5 votes vote down vote up
public synchronized void setWindowDeactivationTime(Window w, long time) {
    AppContext ctx = getAppContext(w);
    if (ctx == null) {
        return;
    }
    @SuppressWarnings("unchecked")
    WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY);
    if (map == null) {
        map = new WeakHashMap<Window, Long>();
        ctx.put(DEACTIVATION_TIMES_MAP_KEY, map);
    }
    map.put(w, time);
}
 
Example 32
Project: openjdk-jdk10   File: ORBImpl.java   View source code 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
Project: galop   File: ServerImpl.java   View source code 5 votes vote down vote up
@Inject
ServerImpl(final ProxySocketFactory proxySocketFactory, final TargetSocketFactory targetSocketFactory,
           final ConnectionHandlerFactory connectionHandlerFactory, final ExecutorService executorService) {
    this.proxySocketFactory = checkNotNull(proxySocketFactory, "proxySocketFactory");
    this.targetSocketFactory = checkNotNull(targetSocketFactory, "targetSocketFactory");
    this.connectionHandlerFactory = checkNotNull(connectionHandlerFactory, "connectionHandlerFactory");
    this.executorService = checkNotNull(executorService, "executorService");
    this.connectionHandlers = Collections.newSetFromMap(new WeakHashMap<>());
}
 
Example 34
Project: boohee_v5.6   File: SuggestionsAdapter.java   View source code 5 votes vote down vote up
public SuggestionsAdapter(Context context, SearchView searchView, SearchableInfo searchable, WeakHashMap<String, ConstantState> outsideDrawablesCache) {
    super(context, searchView.getSuggestionRowLayout(), null, true);
    this.mSearchView = searchView;
    this.mSearchable = searchable;
    this.mCommitIconResId = searchView.getSuggestionCommitIconResId();
    this.mProviderContext = context;
    this.mOutsideDrawablesCache = outsideDrawablesCache;
}
 
Example 35
Project: CSipSimple   File: MenuWrapper.java   View source code 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 36
Project: bskyblock   File: FlyingMobEvents.java   View source code 5 votes vote down vote up
/**
 * @param plugin
 */
public FlyingMobEvents(BSkyBlock plugin) {
    this.plugin = plugin;
    this.mobSpawnInfo = new WeakHashMap<>();

    plugin.getServer().getScheduler().runTaskTimer(plugin, () -> {
        //Bukkit.getLogger().info("DEBUG: checking - mobspawn size = " + mobSpawnInfo.size());
        Iterator<Entry<Entity, Island>> it = mobSpawnInfo.entrySet().iterator();
        while (it.hasNext()) {
            Entry<Entity, Island> entry = it.next();
            if (entry.getKey() == null) {
                //Bukkit.getLogger().info("DEBUG: removing null entity");
                it.remove();
            } else {
                if (entry.getKey() instanceof LivingEntity) {
                    if (!entry.getValue().inIslandSpace(entry.getKey().getLocation())) {
                        //Bukkit.getLogger().info("DEBUG: removing entity outside of island");
                        it.remove();
                        // Kill mob
                        LivingEntity mob = (LivingEntity)entry.getKey();
                        mob.setHealth(0);
                        entry.getKey().remove();
                    } else {
                        //Bukkit.getLogger().info("DEBUG: entity " + entry.getKey().getName() + " is in island space");
                    }
                } else {
                    // Not living entity
                    it.remove();
                }
            }
        }
    }, 20L, 20L);
}
 
Example 37
Project: OpenJSharp   File: RemoteObjectInvocationHandler.java   View source code 5 votes vote down vote up
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 38
Project: openjdk-jdk10   File: GraphPrinterDumpHandler.java   View source code 5 votes vote down vote up
private void ensureInitialized(Graph graph) {
    if (printer == null) {
        if (failuresCount >= FAILURE_LIMIT) {
            return;
        }
        previousInlineContext = new ArrayList<>();
        inlineContextMap = new WeakHashMap<>();
        DebugContext debug = graph.getDebug();
        try {
            printer = printerSupplier.get(graph);
        } catch (IOException e) {
            handleException(debug, e);
        }
    }
}
 
Example 39
Project: openjdk-systemtest   File: HashtableCreator.java   View source code 5 votes vote down vote up
private Map<Object,Object> getWeakHashMap(Map<Object,Object> backingMap) {
	/*
	 * Construct a weak hash map by copying the backingMap
	 * The backing map must be kept alive as long as the returned map is
	 * in scope, otherwise the contents will all end up garbage collected.
	 * Track the WeakhashMap using a PhantomReference queue, so that the 
	 * backingmaps can be freed when the WeakHashMap has been GC.
	 */
	WeakHashMap<Object,Object> rv = new WeakHashMap<Object,Object>(backingMap);
	PhantomReference<WeakHashMap<Object,Object>> ref =
			new PhantomReference<WeakHashMap<Object,Object>>(rv, backingMapQueue);
	
	synchronized(backingMaps){
		backingMaps.put(ref, backingMap);
	}
	
	return rv;
}
 
Example 40
Project: guava-mock   File: GcFinalizationTest.java   View source code 5 votes vote down vote up
public void testAwaitDone_FinalizationPredicate() {
  final WeakHashMap<Object, Object> map = new WeakHashMap<Object, Object>();
  map.put(new Object(), Boolean.TRUE);
  GcFinalization.awaitDone(new FinalizationPredicate() {
    public boolean isDone() {
      return map.isEmpty();
    }
  });
  assertTrue(map.isEmpty());
}