-1

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;
            }
        });
mwengler
  • 2,738
  • 1
  • 19
  • 32

4 Answers4

4

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;
            }
        });
    }
}
323go
  • 14,143
  • 6
  • 33
  • 41
1

As you are using it as flag, you should use the volatile keyword and set it as a variable of your class(instead of a local variable, as you did). Caution, a volatile variable should only be modified by a unique thread. If you want to modify it by more than one thread, you should take a look at synchronisation or atomic objects.

Quanturium
  • 5,698
  • 2
  • 30
  • 36
0

You can access a field within multiple threads by instancing it outside your method (this way, not a "local variable").

private int sharedInt = 0;

public void someMethod() {

    // sharedInt will be visible inside this thread.
    Thread thread = new Thread(new Runnable() {....});

}
Jean Waghetti
  • 4,711
  • 1
  • 18
  • 28
0

How can Runnable modify a final local variable

It can't. Your code sample doesn't compile unless the variable is a member variable, not a local variable.

cannot assign a value to final variable uiIsRunning

Not a real question.

user207421
  • 305,947
  • 44
  • 307
  • 483