Search code examples
javaandroidmultithreadingfinalvolatile

How can Runnable modify a final local variable


I was trying to find out when my user interface is running and had the clever idea of posting a runnable to the uiThread whose only job would be to set a flag. I tried to use a volatile keyword on uiIsRunning but eclipse won't allow that and I don't understand that yet.

But what is amazing to me is when I tried the code below without the final modifier on uiIsRunning, I was told correctly that I could only use a local variable in an embedded class if that local variable is final. So I made uiIsRunning final and much to my surprise, Eclipse is totally fine with my line uiIsRunning = true;, that is Eclipse thinks it is fine for me to be setting the value of my final variable inside this nested class!

If anybody can tell me what I need to do to get the action I want: set a flag to false in my current thread which is then set to true when the thread I am posting it to executes it, I would be grateful.

        final boolean uiIsRunning = false;
        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                uiIsRunning = true;
            }
        });

Solution

  • It is peculiar that you seem to be able to modify a final variable. But more to the point, what you can do in your case is the following:

    public class SurroundingActivity extends Activity {
    
        volatile boolean uiIsRunning = false;
        private Handler uiHandler;
    
        void someMethod () { 
            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    SurroundingActivity.this.uiIsRunning = true;
                }
            });
        }
    }