Synchronization between different threads/processes in Java or Android?
<p>My application has an activity, an service, and several event receivers.</p>

<p>They seems to be controlled by different processes or threads, so I have to figure out a way to synchronize my global variables. </p>

<p>The method I use is the shared preference in android which provide a way to store/read the information in a simple database.</p>

<p>However, I found there might be synchronization issues due to the different processes/threads may happen to read/write the shared preference at the same time.</p>

<p>It might cause the following ANR (application not responding) issue when I receive some events.</p>

<pre>
DALVIK THREADS:
"main" prio=5 tid=1 NATIVE
  | group="main" sCount=1 dsCount=0 s=N obj=0x4001d8b0 self=0xcd30
  | sysTid=4899 nice=0 sched=0/0 cgrp=default handle=-1345017808
  | schedstat=( 1374573162 1397685629 3862 )
  at org.apache.harmony.luni.platform.OSFileSystem.openImpl(Native Method)
  at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:152)
  at java.io.FileOutputStream.(FileOutputStream.java:97)
  at java.io.FileOutputStream.(FileOutputStream.java:69)
  at android.app.ContextImpl$SharedPreferencesImpl.createFileOutputStream(ContextImpl.java:3034)
  at android.app.ContextImpl$SharedPreferencesImpl.writeFileLocked(ContextImpl.java:3094)
  at android.app.ContextImpl$SharedPreferencesImpl.access$300(ContextImpl.java:2824)
  at android.app.ContextImpl$SharedPreferencesImpl$EditorImpl.commit(ContextImpl.java:3009)
  at com.test.myapp.myapp.c((null):-1)
  at com.test.myapp.myapp.a((null):-1)
  at com.test.myapp.EventNetwork.onReceive((null):-1)
  at android.app.ActivityThread.handleReceiver(ActivityThread.java:2810)
  at android.app.ActivityThread.access$3200(ActivityThread.java:125)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2083)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:123)
  at android.app.ActivityThread.main(ActivityThread.java:4627)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:521)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
  at dalvik.system.NativeStart.main(Native Method)
</pre>

<p>I'm not sure my activity, service, or receivers are controlled by the different processes ,or just different threads in the same process. </p>

<p>So, I think that I may need a global mutex to avoid those processes/threads from reading/writing the shared preference at the same time.</p>

<p>Thanks for any responses or suggestions.</p>
