Map<Key, Value> map = new WeakHashMap<Key, Value>(); Key key = new Key(); Value value = new Value(); map.put(key, value); // this will leak value.key = key; pb1: leaking the key
WeakHashMap<String, Object>(); String safeKey1 = new String("I'm not pooled"); String safeKey2 = (new StringBuffer()).append("I'm not pooled either").toString(); String unsafeKey1 = new String("I'll be pooled"); map.put(safeKey1, new Object()); map.put(safeKey2, new Object()); unsafeKey1.intern(); map.put(unsafeKey1, new Object()); safeKey1 = null; safeKey2 = null; unsafeKey1 = null;
final int low = -128; static final int high; static final Integer cache[]; Map<Integer, Object> map = new WeakHashMap<Integer, Object>(); for (int i=0; i < 128; i++) { map.put(i, new Object()); }
new Object(); Object key2 = new Object(); map.put(key, "xyz"); map.put(key2, "GC'd entry"); int scannedElements = 0; for (Map.Entry<Object, String> entry : map.entrySet()) { scannedElements++; key2 = null; System.gc(); // assume GC is triggered } what's the value of scannedElements?
new WeakReference<Object>(referent); referent = null; Runtime.getRuntime().gc(); // Hint to run the GC if (reference.get() == null) { //The garbage collector deleted my referent } else { // referent object is still here }
Object key = new Object(); StringBuilder value = new StringBuilder("leaky"); map.put(key, value); WeakReference<StringBuilder> valueWatcher = new WeakReference<StringBuilder>(value); key = null; value = null; System.gc(); // assume GC run assertNotNull(valueWatcher.get());//should be null!!
activity.onStart(); ReferenceQueue<Activity.Listener> referenceQueue = new ReferenceQueue<Activity.Listener>(); PhantomReference<Activity.Listener> reference = new PhantomReference<Activity.Listener>(service. listener, referenceQueue); activity.onStop(); activity = null; // at this point we removed the strong reference to our Activity, service should not leak the Activity & Activity should be GC'd Runtime.getRuntime().gc(); Reference<?> ref = referenceQueue.remove(TimeUnit.SECONDS.toMillis(10)); assertNotNull(ref); ref.clear(); code here: https://gist.github.com/nhachicha/4ba780712a7ae179cc67
the PendingIntent as a Bundle argument (it's Parcelable) 2. Service invoke PendingIntent.send 3. onActivityResult will be called Survive configuration changes!
a Handler 2. create a messenger from a Handler new Messenger(handler) 3. pass the Messenger as a Bundle argument 4. Service invoke Messenger.send 5. Handler will receive the Message
a Handler 2. create a ResultReceiver using the Handler new ResultReceiver(handler) 3. override onReceiveResult to receive msg 4. pass the ResultReceiver as a Bundle args 5. Service invoke ResultReceiver.send 6. onReceiveResult will be called
a BroadcastReceiver 2. LocalBroadcastManager.getInstance(this). registerReceiver(receiver, filter); 3. Service is ready to broadcast LocalBroadcastManager.getInstance(this). sendB (intent);