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; }
/** * 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; }
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(); }
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(); }
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); }
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); }
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; }
/** * 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); } }
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()); } }
/** * 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; }
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; }; }; }
/** * 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<>(); }
public JavaScriptModuleRegistry(List<JavaScriptModuleRegistration> config) { mModuleInstances = new WeakHashMap<>(); mModuleRegistrations = new HashMap<>(); for (JavaScriptModuleRegistration registration : config) { mModuleRegistrations.put(registration.getModuleInterface(), registration); } }
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(); }
/** * 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; }
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; }
/** * 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>>(); }
/** * 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; } }
/** * 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); }
/** * 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); }
/** Creates a new instance of TimesCollectorPeer */ private TimesCollectorPeer() { files = new ArrayList<Reference<Object>>(); fo2Key2Desc = new WeakHashMap<Object, Map<String, Description>>(); pcs = new PropertyChangeSupport(this); }
/** */ private void addDisplay(final TestSession session) { if (displaysMap == null) { displaysMap = new WeakHashMap<TestSession,Boolean>(4); } displaysMap.put(session, Boolean.TRUE); }
@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(); }
private void initTransients() { rmbscMap = new WeakHashMap<Subject, WeakReference<MBeanServerConnection>>(); connected = false; terminated = false; connectionBroadcaster = new NotificationBroadcasterSupport(); }
@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); } } }
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(); } }); }
/** * 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)); }
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)); } } }); }
/** * 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; } }
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); }
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); }
@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<>()); }
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; }
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); }
/** * @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); }
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; } }; }
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); } } }
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()); }