Search code examples
javarunnable

How to make a Runnable Change a given value


So the problem I am currently facing is that I want to write a method, that creates a runnable that changes a given Value; in this case it's a Boolean Object.

(I use this, to make it possible to react on different ways to a Key Press)

If I am just using a Method of the passed Object it works just fine.

However:

public static Runnable createOnOffSwitchRunnable(Boolean b)
{
    final Boolean Reference = b;
    Runnable R = new Runnable()
    {
        public void run()
        {
            if (Reference.booleanValue() == true)
            {
                Reference = false;
            }
        }
    };
    return R;
}

Obviously this does not work, as I can't directly assign a value to the final Variable and the Boolean Object has no "set"-method. However I NEED to declare it final to even be able to create the Runnable.

So is there no way how you can change a passed value, with a runnable? (it would be nice if I could keep on using standard java Types instead of "inventing" some new class)

If so, are there any alternatives for saving and passing methods?

Any help would be appreciated (:


Solution

  • The local variable you call Reference exists only while createOnOffSwitchRunnable is running and disappears when it returns; it makes no sense to modify it. You can modify an instance variable though, if it makes sense in your case. If you do this you should declare the variable volatile to prevent stale reads (also called "the law of the blind spot").

    volatile Boolean Reference;
    
    public static Runnable createOnOffSwitchRunnable(Boolean b)
    {
        Reference = b;
    
        Runnable R = new Runnable()
        {
            public void run()
            {
                if (Reference.booleanValue() == true)
                {
                    Reference = false;
                }
            }
        };
        return R;
    }
    

    Another option is making Reference an instance variable in the Runnable. This might also solve your problem, I have no idea what you're trying to do.

    public static Runnable createOnOffSwitchRunnable(final Boolean b)
    {
    
        Runnable R = new Runnable()
        {
            private Boolean Reference = b;
    
            public void run()
            {
                if (Reference.booleanValue() == true)
                {
                    Reference = false;
                }
            }
        };
        return R;
    }
    

    (Also, please use standard naming conventions, written it title case Reference looks like the name of a class.)