In MusicSync, one of the views became complex and too slow to be inflated on the UI thread.

So, I decided to do some Pooling around it to inflate it on the background thread and use it on the UI thread. This made the UI snappier, reducing multiple-second load times when opening some folders.

However, soon I ended up with an edge case where re-opening the activity (and not the app) led to a semi-functional app. This edge case is hard as it gets triggered only in particular scenarios where the user destroys the activity via swipe up. At the same time, the app keeps running due to the attached foreground service that’s playing the media. And on activity re-creation, I got stale views!

Once I diagnosed the issue, the fix was simple. Tie the views’s lifecycle to the current Activity’s context. This ensures that you don’t get stale views.

Java
1
2
3
4
5
// Broken code
private static final Stack<View> sMediaFileViewPool = new Stack<>();

// Fixed code
private static final WeakHashMap<Context, Stack<View>> sMediaFileViewPool = new WeakHashMap<>();