androidandroid-activitysharedpreferencesapply

SharedPreferences.apply() and ANR application


I used to SharedPreferences.apply() method. When this method is called very often, then it hangs the application. Commit() method is very slow, but is working properly.

You can get the ANR in my example. Fold and unfold the activity!

public class Main extends Activity {

@Override
public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.main);

    new Thread(new Runnable() {
        @Override
        public void run() {

            while(true) {
                SharedPreferences.Editor ed = getEditor();
                ed.putString(getUUID(), getUUID());
                ed.apply();


                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
}



public static String getUUID() {
    return UUID.randomUUID().toString();
}


final private String BASE = "BASE";
private SharedPreferences shadPrefBase = null;
SharedPreferences getSharedPreferences() {
    if(shadPrefBase == null) {
        shadPrefBase = getSharedPreferences(BASE, Context.MODE_MULTI_PROCESS);
    }
    return shadPrefBase;
}


private SharedPreferences.Editor editorShared = null;
private SharedPreferences.Editor getEditor() {
    if(editorShared == null) {
        editorShared = getSharedPreferences().edit();
    }
    return editorShared;
}
}

Fold and unfold the activity!


Solution

  • Every 10 milliseconds, indefinitely, you are forking a background thread adding an asynchronous job via the apply() call, all of which are going to queue up as they attempt to do I/O on the same data. That is not going to give you good results.

    Beyond that, I would be very careful about sharing Editor instances across threads the way you are.