public T instance() { T singletonInstancePerThread = null; // use weak reference to prevent cyclic reference during GC WeakReference<T> ref = (WeakReference<T>) perThreadCache.get(); // singletonInstancePerThread=perThreadCache.get(); // if (singletonInstancePerThread==null) { if (ref == null || ref.get() == null) { Class<T> clazz = null; try { clazz = (Class<T>) Thread.currentThread().getContextClassLoader().loadClass(singletonClassName); singletonInstancePerThread = clazz.newInstance(); } catch (Exception ignore) { try { clazz = (Class<T>) Class.forName(singletonClassName); singletonInstancePerThread = clazz.newInstance(); } catch (Exception ignore2) { } } perThreadCache.set(new WeakReference<T>(singletonInstancePerThread)); } else { singletonInstancePerThread = ref.get(); } return singletonInstancePerThread; }
@Override public void addSources(List<TaskSource> sources) { checkNotNull(sources, "sources is null"); checkState( !Thread.holdsLock(this), "Can not add sources while holding a lock on the %s", getClass().getSimpleName()); try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) { // update our record of sources and schedule drivers for new partitioned splits Map<PlanNodeId, TaskSource> updatedUnpartitionedSources = updateSources(sources); // tell existing drivers about the new splits; it is safe to update drivers // multiple times and out of order because sources contain full record of // the unpartitioned splits for (TaskSource source : updatedUnpartitionedSources.values()) { // tell all the existing drivers this source is finished for (WeakReference<Driver> driverReference : drivers) { Driver driver = driverReference.get(); // the driver can be GCed due to a failure or a limit if (driver != null) { driver.updateSource(source); } else { // remove the weak reference from the list to avoid a memory leak // NOTE: this is a concurrent safe operation on a CopyOnWriteArrayList drivers.remove(driverReference); } } } } }
/** * Called after an operation executing in the background is completed. It sets the bitmap image to * an image view and dismisses the progress dialog. * * @param image The bitmap image */ protected void onPostExecute(Bitmap image) { // Dismiss the progress dialog. mActivity.get().dismissDialog(); // Display the downloaded image to the user. mActivity.get().displayBitmap(image); }
public static ArrayList<Object[]> findClosestNodes( TileVisNode target, TileVisNode root, ArrayList<Object[]> in) { TileVisNode closestChild = null; for (WeakReference<TileVisNode> child : root.getChildren()) { TileVisNode n = child.get(); if (n != null && !n.equals(target) && !n.equals(root) && (target.getAttunement() == -1 || n.getAttunement() == -1 || n.getAttunement() == target.getAttunement())) { float r2 = inRange(n.getWorldObj(), n.getLocation(), target.getLocation(), target.getRange()); if (r2 > 0) { in.add(new Object[] {n, r2}); } in = findClosestNodes(target, n, in); } } return in; }
public static DomainInfo getInstance(String tld) { if (tld != null) { String lcaseTld = tld.toLowerCase(Locale.ENGLISH); int index = lcaseTld.indexOf(" "); if (index > 0) { // for examle recaptcha.com (google) lcaseTld = lcaseTld.substring(0, index); } index = lcaseTld.indexOf("/"); if (index > 0) { // for examle recaptcha.com/bla lcaseTld = lcaseTld.substring(0, index); } synchronized (CACHE) { DomainInfo ret = null; WeakReference<DomainInfo> domainInfo = CACHE.get(lcaseTld); if (domainInfo == null || (ret = domainInfo.get()) == null) { ret = new DomainInfo(lcaseTld); CACHE.put(lcaseTld, new WeakReference<DomainInfo>(ret)); } return ret; } } return null; }
XPathSupport getXPathSupport() { if (jaxenXPathSupport != null) { return jaxenXPathSupport; } XPathSupport xps = null; Document doc = node.getOwnerDocument(); if (doc == null) { doc = (Document) node; } synchronized (doc) { WeakReference ref = (WeakReference) xpathSupportMap.get(doc); if (ref != null) { xps = (XPathSupport) ref.get(); } if (xps == null) { try { xps = (XPathSupport) xpathSupportClass.newInstance(); xpathSupportMap.put(doc, new WeakReference(xps)); } catch (Exception e) { logger.error("Error instantiating xpathSupport class", e); } } } return xps; }
@Override protected void notifyUpdate(Iterable<PicItem> entities) { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); for (PicItem entity : entities) { Long key = getKey(entity); if (key != null) { notifyExtraOb(key); ops.add( ContentProviderOperation.newUpdate(ContentUris.withAppendedId(CONTENT_URI, key)) .withValue(null, null) .build()); } } try { if (contextWeakReference.get() != null) contextWeakReference.get().getContentResolver().applyBatch(AUTHORITY, ops); } catch (RemoteException e) { e.printStackTrace(); } catch (OperationApplicationException e) { e.printStackTrace(); } }
private boolean cleanupRequestor(long now) { boolean empty = true; int x = 0; for (int i = 0; i < requestorNodes.length; i++) { WeakReference<? extends PeerNodeUnlocked> ref = requestorNodes[i]; if (ref == null) continue; PeerNodeUnlocked pn = ref.get(); if (pn == null) continue; long bootID = pn.getBootID(); if (bootID != requestorBootIDs[i]) continue; if (!pn.isConnected()) continue; if (now - requestorTimes[i] > MAX_TIME_BETWEEN_REQUEST_AND_OFFER) continue; empty = false; requestorNodes[x] = requestorNodes[i]; requestorTimes[x] = requestorTimes[i]; requestorBootIDs[x] = requestorBootIDs[i]; requestorHTLs[x] = requestorHTLs[i]; x++; } if (x < requestorNodes.length) { requestorNodes = Arrays.copyOf(requestorNodes, x); ; requestorTimes = Arrays.copyOf(requestorTimes, x); ; requestorBootIDs = Arrays.copyOf(requestorBootIDs, x); ; requestorHTLs = Arrays.copyOf(requestorHTLs, x); ; } return empty; }
public static synchronized Activity getActivity() { Activity result = null; if (instanceRef != null && instanceRef.get() != null) { result = instanceRef.get(); } return result; }
@Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: Activity activity = mActivity.get(); BaseLoopView loopView = mLoopView.get(); if (activity != null && loopView != null) { if (!loopView.isAutoScroll()) return; int change = (loopView.getDirection() == BaseLoopView.LEFT) ? -1 : 1; loopView .getViewPager() .setCurrentItem(loopView.getViewPager().getCurrentItem() + change, true); loopView.sendScrollMessage(loopView.getInterval()); } else { removeMessages(0); if (loopView != null) { loopView.releaseResources(); } } default: break; } }
/* */ public synchronized void close() /* */ throws IOException /* */ { /* 399 */ boolean bool1 = logger.traceOn(); /* 400 */ boolean bool2 = logger.debugOn(); /* */ /* 402 */ if (bool1) logger.trace("close", "closing"); /* */ /* 404 */ Object localObject1 = null; /* */ try { /* 406 */ if (bool2) logger.debug("close", "closing Server"); /* 407 */ closeServer(); /* */ } catch (IOException localIOException1) { /* 409 */ if (bool1) logger.trace("close", "Failed to close server: " + localIOException1); /* 410 */ if (bool2) logger.debug("close", localIOException1); /* 411 */ localObject1 = localIOException1; /* */ } /* */ /* 414 */ if (bool2) logger.debug("close", "closing Clients"); /* */ while (true) /* */ { /* 417 */ synchronized (this.clientList) { /* 418 */ if (bool2) logger.debug("close", "droping dead references"); /* 419 */ dropDeadReferences(); /* */ /* 421 */ if (bool2) logger.debug("close", "client count: " + this.clientList.size()); /* 422 */ if (this.clientList.size() == 0) /* */ { /* */ break; /* */ } /* */ /* 428 */ Iterator localIterator = this.clientList.iterator(); /* 429 */ if (localIterator.hasNext()) { /* 430 */ WeakReference localWeakReference = (WeakReference) localIterator.next(); /* 431 */ RMIConnection localRMIConnection = (RMIConnection) localWeakReference.get(); /* 432 */ localIterator.remove(); /* 433 */ if (localRMIConnection != null) { /* */ try { /* 435 */ localRMIConnection.close(); /* */ } catch (IOException localIOException2) { /* 437 */ if (bool1) /* 438 */ logger.trace("close", "Failed to close client: " + localIOException2); /* 439 */ if (bool2) logger.debug("close", localIOException2); /* 440 */ if (localObject1 == null) { /* 441 */ localObject1 = localIOException2; /* */ } /* */ } /* */ } /* */ } /* */ } /* */ } /* */ /* 449 */ if (this.notifBuffer != null) { /* 450 */ this.notifBuffer.dispose(); /* */ } /* 452 */ if (localObject1 != null) { /* 453 */ if (bool1) logger.trace("close", "close failed."); /* 454 */ throw localObject1; /* */ } /* */ /* 457 */ if (bool1) logger.trace("close", "closed."); /* */ }
/* */ protected void clientClosed(RMIConnection paramRMIConnection) /* */ throws IOException /* */ { /* 338 */ boolean bool = logger.debugOn(); /* */ /* 340 */ if (bool) logger.trace("clientClosed", "client=" + paramRMIConnection); /* */ /* 342 */ if (paramRMIConnection == null) { /* 343 */ throw new NullPointerException("Null client"); /* */ } /* 345 */ synchronized (this.clientList) { /* 346 */ dropDeadReferences(); /* 347 */ Iterator localIterator = this.clientList.iterator(); /* 348 */ while (localIterator.hasNext()) { /* 349 */ WeakReference localWeakReference = (WeakReference) localIterator.next(); /* 350 */ if (localWeakReference.get() == paramRMIConnection) { /* 351 */ localIterator.remove(); /* 352 */ break; /* */ } /* */ /* */ } /* */ /* */ } /* */ /* 360 */ if (bool) logger.trace("clientClosed", "closing client."); /* 361 */ closeClient(paramRMIConnection); /* */ /* 363 */ if (bool) logger.trace("clientClosed", "sending notif"); /* 364 */ this.connServer.connectionClosed( paramRMIConnection.getConnectionId(), "Client connection closed", null); /* */ /* 367 */ if (bool) logger.trace("clientClosed", "done"); /* */ }
@Override public void deliverError(VolleyError error) { super.deliverError(error); if (mListenerReference != null && mListenerReference.get() != null) { NetworkListener listener = mListenerReference.get(); BaseError response = new BaseError(); if (error.networkResponse != null) { response.mStatusCode = error.networkResponse.statusCode; response.mErrorMessage = new String(error.networkResponse.data); } else if (error instanceof NetworkError || error instanceof NoConnectionError) { response.mErrorMessage = "Please check the internet connection"; } else if (error instanceof TimeoutError) { response.mErrorMessage = "Server is busy try again later"; } else if (error instanceof AuthFailureError) { response.mErrorMessage = "Auth Failure"; } else if (error instanceof ServerError) { response.mErrorMessage = "ServerError"; } else if (error instanceof ParseError) { response.mErrorMessage = "Error in parsing server data"; } listener.onError(response); } }
@Override protected void deliverResponse(T response) { if (mListenerReference != null && mListenerReference.get() != null) { NetworkListener listener = mListenerReference.get(); listener.onSuccess(response); } }
private final Collection<ICompilationUnit> collectAssociatedCompilationUnits( IFileSpecification file) { String filename = file.getPath(); Collection<WeakReference<ICompilationUnit>> relatedCompilationUnits = pathToCompilationUnitMapping.getVisibleAndInvisible(filename); // relatedCompilationUnits should never be null, but it is OK for it to be empty, as // we can be null, if someone passes us in a arbitrary file which has no compilation // units associated with it. assert (relatedCompilationUnits != null) : "relatedCompilationUnits should never be null"; // add any compilation units which include the file, as they need to be recompiled also Collection<WeakReference<ICompilationUnit>> includingCompilationUnits = includeFilesToIncludingCompilationUnitMapping.get(filename); Collection<WeakReference<ICompilationUnit>> allRelatedCompilationUnits = new HashSet<WeakReference<ICompilationUnit>>(); allRelatedCompilationUnits.addAll(relatedCompilationUnits); allRelatedCompilationUnits.addAll(includingCompilationUnits); HashSet<ICompilationUnit> associatedCompilationUnits = new HashSet<ICompilationUnit>(); for (WeakReference<ICompilationUnit> relatedCURef : allRelatedCompilationUnits) { ICompilationUnit relatedCU = relatedCURef.get(); if (relatedCU != null) { associatedCompilationUnits.add(relatedCU); } } final Set<ICompilationUnit> associatedCompilationUnitsAccountingForConflictingDefinitions = ASProjectScope.getCompilationUnitsWithConflictingDefinitions( this, associatedCompilationUnits); return associatedCompilationUnitsAccountingForConflictingDefinitions; }
@Override public synchronized Component getComponentByURI(URI id) { WeakReference<Component> componentRef = uriToComponent.get(id); if (componentRef == null) return null; // Might also be null it reference has gone dead return componentRef.get(); }
public static synchronized Context getInstance() { if (instanceRef == null || instanceRef.get() == null) { return BaseApplication.getContext(); } else { return instanceRef.get(); } }
private void fetchComments() { try { final URL newUrl = new URL(book.get().getCommentsUrl()); // sax stuff final SAXParserFactory factory = SAXParserFactory.newInstance(); final SAXParser parser = factory.newSAXParser(); final XMLReader reader = parser.getXMLReader(); // initialize our parser logic final CommentsHandler commentsHandler = new CommentsHandler(book.get().getComments()); reader.setContentHandler(commentsHandler); // get the xml feed reader.parse(new InputSource(newUrl.openStream())); } catch (MalformedURLException e) { COMMENTS_ERROR = MALFORMED_URL; Log.e(TAG, "MalformedURLException: " + e + "\nIn fetchComments()"); } catch (ParserConfigurationException pce) { COMMENTS_ERROR = PARSER_CONFIG_ERROR; Log.e(TAG, "ParserConfigurationException: " + pce + "\nIn fetchComments()"); } catch (SAXException se) { COMMENTS_ERROR = SAX_ERROR; Log.e(TAG, "SAXException: " + se + "\nIn fetchComments()"); } catch (IOException ioe) { COMMENTS_ERROR = IO_ERROR; Log.e(TAG, "IOException: " + ioe + "\nIn fetchComments()"); } }
/** Have we asked this peer for the key? */ public synchronized boolean askedFromPeer(PeerNodeUnlocked peer, long now) { boolean anyValid = false; boolean ret = false; for (int i = 0; i < requestedNodes.length; i++) { WeakReference<? extends PeerNodeUnlocked> ref = requestedNodes[i]; if (ref == null) continue; PeerNodeUnlocked pn = ref.get(); if (pn == null) { requestedNodes[i] = null; continue; } long bootID = pn.getBootID(); if (bootID != requestedBootIDs[i]) { requestedNodes[i] = null; continue; } anyValid = true; if (now - requestedTimes[i] < MAX_TIME_BETWEEN_REQUEST_AND_OFFER) { if (pn == peer) ret = true; anyValid = true; } } if (!anyValid) { requestedNodes = EMPTY_WEAK_REFERENCE; requestedTimes = requestedBootIDs = requestedTimeoutsRF = requestedTimeoutsFT = EMPTY_LONG_ARRAY; requestedTimeoutHTLs = EMPTY_SHORT_ARRAY; } return ret; }
@SuppressWarnings("unchecked") void check() { watchDogRuns++; long current = System.currentTimeMillis(); ArrayList<WeakReference<TimeoutMgmHandle>> connectionsCopy = null; synchronized (handles) { connectionsCopy = (ArrayList<WeakReference<TimeoutMgmHandle>>) handles.clone(); } for (WeakReference<TimeoutMgmHandle> handleRef : connectionsCopy) { TimeoutMgmHandle handle = handleRef.get(); if (handle == null) { remove(handleRef); } else { NonBlockingConnection con = handle.getConnection(); if (con.isOpen()) { checkTimeout(con, current); } else { remove(handleRef); } } } computeSize(); }
public synchronized short minRequestorHTL(short htl) { long now = System.currentTimeMillis(); boolean anyValid = false; for (int i = 0; i < requestorNodes.length; i++) { WeakReference<? extends PeerNodeUnlocked> ref = requestorNodes[i]; if (ref == null) continue; PeerNodeUnlocked pn = ref.get(); if (pn == null) { requestorNodes[i] = null; continue; } long bootID = pn.getBootID(); if (bootID != requestorBootIDs[i]) { requestorNodes[i] = null; continue; } if (now - requestorTimes[i] < MAX_TIME_BETWEEN_REQUEST_AND_OFFER) { if (requestorHTLs[i] < htl) htl = requestorHTLs[i]; } anyValid = true; } if (!anyValid) { requestorNodes = EMPTY_WEAK_REFERENCE; requestorTimes = requestorBootIDs = EMPTY_LONG_ARRAY; ; requestorHTLs = EMPTY_SHORT_ARRAY; } return htl; }
protected void onSignOut(Activity currentActivity) { if (currentActivity == null) { Log.e(TAGERROR, "Activity can not be null"); } else { changeCurrentState(StatusFacebookConn.DISCONNECTED); Log.i(TAGINFO, "Disconnected"); LoginManager.getInstance().logOut(); activityWeakReference .get() .getSharedPreferences("FacebookSession", Context.MODE_PRIVATE) .edit() .putBoolean("FacebookLogged", false) .commit(); activityWeakReference .get() .getSharedPreferences("FacebookSession", Context.MODE_PRIVATE) .edit() .putString("FacebookEmail", null) .commit(); currentActivity.startActivity(new Intent(currentActivity, LoginActivity.class)); activityWeakReference.get().finish(); currentActivity.finish(); clearInstanceReference(); } }
public void removeListener(final ListenerType t) { if (t == null) { return; } synchronized (this.LOCK) { if (weakListener.size() > 0) { ListenerType l = null; final java.util.List<WeakReference<ListenerType>> newWeakListener = new ArrayList<WeakReference<ListenerType>>(this.weakListener.size()); for (final WeakReference<ListenerType> listener : this.weakListener) { if ((l = listener.get()) == null) { /* weak item is gone */ continue; } else if (l != t) { newWeakListener.add(listener); } } this.weakListener = newWeakListener; } /* remove strong item */ if (strongListeners.contains(t)) { final java.util.List<ListenerType> newStrongListener = new ArrayList<ListenerType>(this.strongListeners); newStrongListener.remove(t); this.strongListeners = newStrongListener; } } }
public synchronized void cleanupCurrentThread() { final long id = Thread.currentThread().getId(); for (final ConcreteResource res : new HashSet<ConcreteResource>(lock.keySet())) { final WeakReference<Thread> ref = lock.get(res); if (ref != null) { boolean rm = false; if (ref.get() == null) { logger.debug( "Cleaning up lock: {} for thread: {}", res, Thread.currentThread().getName()); rm = true; } else if (ref.get().getId() == id) { logger.debug( "Cleaning up lock: {} for thread: {}", res, Thread.currentThread().getName()); rm = true; } if (rm) { synchronized (lock) { lock.remove(res); lock.notifyAll(); } } } } }
public void testDroppedThread() throws Exception { this.server.setHttpService(new EchoService()); MultiThreadedHttpConnectionManager mthcm = new MultiThreadedHttpConnectionManager(); client.setHttpConnectionManager(mthcm); WeakReference wr = new WeakReference(mthcm); GetMethod method = new GetMethod("/"); client.executeMethod(method); method.releaseConnection(); mthcm = null; client = null; method = null; System.gc(); // this sleep appears to be necessary in order to give the JVM // time to clean up the miscellaneous pointers to the connection manager try { Thread.sleep(1000); } catch (InterruptedException e) { fail("shouldn't be interrupted."); } Object connectionManager = wr.get(); assertNull("connectionManager should be null", connectionManager); }
public Map<ConcreteResource, CharSequence> getActiveLocks() { final Map<ConcreteResource, CharSequence> active = new HashMap<ConcreteResource, CharSequence>(); for (final ConcreteResource f : lock.keySet()) { final StringBuilder owner = new StringBuilder(); final WeakReference<Thread> ref = lock.get(f); if (ref == null) { owner.append("UNKNOWN OWNER; REF IS NULL."); } final Thread t = ref.get(); if (t == null) { owner.append("UNKNOWN OWNER; REF IS EMPTY."); } else { owner.append(t.getName()); if (!t.isAlive()) { owner.append(" (DEAD)"); } } active.put(f, owner); } return active; }
/** * Returns an instance of NativeLibrary for the specified name. The library is loaded if not * already loaded. If already loaded, the existing instance is returned. * * <p>More than one name may map to the same NativeLibrary instance; only a single instance will * be provided for any given unique file path. * * @param libraryName The library name to load. This can be short form (e.g. "c"), an explicit * version (e.g. "libc.so.6" or "QuickTime.framework/Versions/Current/QuickTime"), or the full * (absolute) path to the library (e.g. "/lib/libc.so.6"). * @param options native library options for the given library (see {@link Library}). */ public static final NativeLibrary getInstance(String libraryName, Map options) { options = new HashMap(options); if (options.get(Library.OPTION_CALLING_CONVENTION) == null) { options.put(Library.OPTION_CALLING_CONVENTION, new Integer(Function.C_CONVENTION)); } // Use current process to load libraries we know are already // loaded by the VM to ensure we get the correct version if ((Platform.isLinux() || Platform.isAIX()) && Platform.C_LIBRARY_NAME.equals(libraryName)) { libraryName = null; } synchronized (libraries) { WeakReference ref = (WeakReference) libraries.get(libraryName + options); NativeLibrary library = ref != null ? (NativeLibrary) ref.get() : null; if (library == null) { if (libraryName == null) { library = new NativeLibrary("<process>", null, Native.open(null, openFlags(options)), options); } else { library = loadLibrary(libraryName, options); } ref = new WeakReference(library); libraries.put(library.getName() + options, ref); File file = library.getFile(); if (file != null) { libraries.put(file.getAbsolutePath() + options, ref); libraries.put(file.getName() + options, ref); } } return library; } }
/** * Notify the {@link ImageProxy} that an image has been loaded. * * @param iconId The id of the image that has been loaded. * @param result The image. */ void imageReady(long iconId, Drawable result) { if (result == null) { return; } synchronized (mImageCache) { // put the icon into the cache mImageCache.put(iconId, result); } Set<WeakReference<ImageAvailableListener>> listeners = null; synchronized (mJobWaitQueue) { listeners = mJobWaitQueue.get(iconId); // all listeners will be notified now, so remove them mJobWaitQueue.remove(iconId); } if (listeners != null) { // notify listeners for (WeakReference<ImageAvailableListener> listenerRef : listeners) { ImageAvailableListener listener = listenerRef.get(); if (listener != null) { listener.imageAvailable(iconId, result); } } } }
/** * This method drains vis from a relay or source near the passed in location. The amount received * can be less than the amount requested so take that into account. * * @param world * @param x the x position of the draining block or entity * @param y the y position of the draining block or entity * @param z the z position of the draining block or entity * @param aspect what aspect to drain * @param amount how much to drain * @return how much was actually drained */ public static int drainVis(World world, int x, int y, int z, Aspect aspect, int amount) { int drainedAmount = 0; WorldCoordinates drainer = new WorldCoordinates(x, y, z, world.provider.dimensionId); if (!nearbyNodes.containsKey(drainer)) { calculateNearbyNodes(world, x, y, z); } ArrayList<WeakReference<TileVisNode>> nodes = nearbyNodes.get(drainer); if (nodes != null && nodes.size() > 0) for (WeakReference<TileVisNode> noderef : nodes) { TileVisNode node = noderef.get(); if (node == null) continue; int a = node.consumeVis(aspect, amount); drainedAmount += a; amount -= a; if (a > 0) { int color = Aspect.getPrimalAspects().indexOf(aspect); generateVisEffect( world.provider.dimensionId, x, y, z, node.xCoord, node.yCoord, node.zCoord, color); } if (amount <= 0) { break; } } return drainedAmount; }
public String cachedValueOf(final String str) { if (str != null && (lengthLimit < 0 || str.length() <= lengthLimit)) { // Return value from cache if available try { lock.readLock().lock(); WeakReference<String> ref = cache.get(str); if (ref != null) { return ref.get(); } } finally { lock.readLock().unlock(); } // Update cache with new content try { lock.writeLock().lock(); WeakReference<String> ref = cache.get(str); if (ref != null) { return ref.get(); } cache.put(str, new WeakReference<>(str)); } finally { lock.writeLock().unlock(); } return str; } return str; }