I want to check whether a value retains its value and take a particular action onChange. I have to constantly check whether the value has changed, so I need it to be a new Runnable
on a separate Thread
.(If this is not the case, please let me know) But I cannot check for the value inside a sub class(inner class) because I will need to declare the value as final
.But the whole point is to not let the variable be final
. The datatype is int
while (true) {
//check whether value has changed
}
Using
new Thread(new Runnable() {
@Override
public void run() {
if(valueHasChanged()){//valueHasChanged will require the variable to be final
yes();
}
}).start();
The above code has been cleaned to remove unecessaty stuff.
Better use a queuing model with a limited number of items, say 1024. This is because the rate of value change might be different than the rate of execution of the yes()
method. Queuing model is simpler and can be extended/tweaked in future if required.
Code will look like this, I have omitted the InterruptedException
catch block for readability:
private final BlockingQueue<Boolean> queue = new LinkedBlockingQueue<>(1024);
while (true) {
.....
//check whether value has changed and do
queue.put(true);
.....
}
....
....
new Thread(new Runnable() {
@Override
public void run() {
while(queue.take()){
yes();
}
}
}).start();