Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Avoiding Memory leaks by Viktor Kifer

Avoiding Memory leaks by Viktor Kifer

Avoiding Memory leaks by Viktor Kifer

GDG Ternopil

July 22, 2015
Tweet

More Decks by GDG Ternopil

Other Decks in Programming

Transcript

  1. Symptoms • Frequent calls to GC • Lesser amount of

    memory reclaimed on each GC • Memory usage increases over time • as a result -> OOM and Response time decreases
  2. Example 1 public class MainActivity extends AppCompatActivity implements SomeListener {

    protected void onCreate(Bundle savedInstanceState) { // … Singleton.getInstance().register(this); } public void onSomeEvent() { // some code here } }
  3. Example 1 public class MainActivity extends AppCompatActivity implements SomeListener {

    protected void onCreate(Bundle savedInstanceState) { // ... Singleton.getInstance().register(this); } // SomeListener interface implementation protected void onDestroy() { // ... Singleton.getInstance().unregister(this); } }
  4. Memory Dump • DDMS - “Dump HPROF file” • android.os.Debug.

    dumpHprofData (“filename”) %sdk%/platform-tools/ hprof-conv
  5. General rules • unregister event listeners • avoid string concatenation

    in loops (use StringBuilder) • avoid unnecessary object creation
  6. General rules (Continue) • close resources in finally blocks (Stream,

    Reader, Connection etc) • set static objects to null
  7. General Rules (Android) • call Bitmap.recycle() • avoid object creation

    on onDraw() • use getApplicationContext() instead of activity context, but only when appropriate
  8. Non-static inner and anonymous classes contain strong reference to their

    outer class public class MyActivity extends Activity { // Anonymous class SomeListener contains strong reference to MyActivity instance Singleton.getInstance().addListener(new SomeListener() { // ... }); }
  9. Example 2 public class HandlerLeakExampleActivity extends AppCompatActivity { private final

    Handler mLeakyHandler = new Handler() { @Override public void handleMessage(Message msg) { // ... } }; }
  10. Example 2 public class HandlerLeakExampleActivity extends AppCompatActivity { private static

    class MyHandler extends Handler { private final WeakReference<HandlerLeakExampleActivity> mActivity; public MyHandler(HandlerLeakExampleActivity activity) { mActivity = new WeakReference<HandlerLeakExampleActivity>(activity); } public void handleMessage(Message msg) { HandlerLeakExampleActivity activity = mActivity.get(); if (activity != null) { // ... } } } private final MyHandler mHandler = new MyHandler(this); }
  11. Q&A