Search code examples
androidsharedpreferences

Does the SharedPreference really have async API for writing in Android?


I've just read an article which is about SharedPreferences and it baffles me. I've believed that SharedPreferences's apply() works asynchronously when it writes until now. You can see the reason here.

But the article which is posted by Florina Muntenescu in the Android Developers Blog said SharedPreferences has a synchronous API that can appear safe to call on the UI thread, but which actually does disk I/O operations. Furthermore, apply() blocks the UI thread on fsync(). There is only async API for reading changed values via listener.

So, What i want to ask are...

  1. is apply() also synchronous method?
  2. the official android document is wrong?

Solution

  • is apply() also synchronous method?

    No. It returns immediately.

    the official android document is wrong?

    Probably not. Florina is pretty good.

    What Florina is saying in that blog post is that a side-effect of apply() is that at some point, the UI thread will be blocked due to the fsync() when the new preference values are written. Think of the side-effect as akin to pollution: the polluter (apply()) is not affected directly, but the pollution still has an impact, just a bit later on.