This has been solved by Robin. Thanks Robin!
The idea behind what I want to do is make a timer that performs an action every X seconds, but X has to change between uses.
Right now I’m doing it like this:
try {
final FileWriter fstream = new FileWriter("timetest.log");
final BufferedWriter out = new BufferedWriter(fstream);
ActionListener task_performer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
critical_requests[0]++;
try {
System.out.println("DEBUG: Critical Section requests: " + critical_requests[0] + "\n");
out.write("Critical Section request:\t" + critical_requests[0] + "\n");
} catch (IOException e) {
System.out.println(e.getMessage() + "\n");
}
((Timer)evt.getSource()).setDelay( 150 + (rand.nextInt(10) * time_unit ));
}
};
new Timer(wait_delay, task_performer).start();
System.out.println("Entering while loop\n");
while(true) {
if(critical_requests[0] >= 60){
try {
out.close();
} catch (IOException e) {
System.out.println("Close failed for some reason:\t" + e.getMessage() + "\n");
System.exit(-1);
}
System.exit(0);
}
//System.out.println("" + critical_requests[0] + "\n"); // Debug
critical_requests[0] = critical_requests[0]; // Java is an insane language and it requires me to have this line here
}
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
The error I get is:
local variable is accessed from within inner class; needs to be declared final
I tried making some of them final, but then I can’t change the values inside of the listener. Plus some of the variables don’t make sense to make final (the BufferedWriter out, rand).
All 5 compiler errors are:
local variable rand is accessed from within inner class; needs to be declared final
one each for out, rand, and wait_delay, and two for critical_requests.
How can I reconcile this?
Looking at your code the problem is the
wait_delayand thecritical_requestsvariable.ActionListener. You will have to set it on theTimeragain before it has any effect on the delay of theTimerTimerobject each time you change thewait_delayvariable will result in a lot ofTimerinstances, which each keep running as aTimerrepeats by default. Only if you have calledsetRepeats( false )they will actually stop. Looking at your comment (which should have been part of the question), you want to update the delay of theTimercritical_requestsvariable inside theActionListener, you can store it in a final arraySo I would suggest to change your code to something like