Skip to content Skip to sidebar Skip to footer

Android Volatile Not Working?

I have an Activity class, in which I have a static flag, let's say public static volatile flag = false; Then in the class, I start a thread, which checks the flag and do different

Solution 1:

I think the problem is that you are running the receiver in its own process. From the docs for the android:process attribute of <receiver>:

If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the broadcast receiver runs in that process.

I think the receiver is modifying a process-local version of TestService.flag, not the one being used by TestService. Try removing the android:process attribute from the <receiver> tag in your manifest.

Solution 2:

From this link

http://www.javamex.com/tutorials/synchronization_volatile.shtml

Essentially, volatile is used to indicate that a variable's value will be modified by different threads.

Solution 3:

I really hope your service thread is not this one (I don't see any other one):

privateclassMyTopThreadextendsThread {

    @Overridepublicvoidrun() {
        while (true) {
            try {
                Thread.sleep(150);
                Log.d(TAG, "Flag is " + TestService.flag);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

}

Because you have while(true) here, not while(!flag) as it should be.

Post a Comment for "Android Volatile Not Working?"