My thoughts as an enterprise Java developer.

Monday, January 15, 2007

Tip: Need to communicate between anonymous inner classes?

Here is a quick tip:
Do you have two anonymous inner classes that need to communicate? I had two anonymous inner classes that implemented Runnable and needed to communicate with a boolean value. Therefore I decided to make a boolean variable in the declaring method but in order for the inner class to access the variable it needs to be declared final. But that would prevent me from changing the variable! I needed a mutable Boolean. Instead of creating a MutableBoolean class I declared the variable as "final boolean[] done = new boolean[]{false};" so that one thread could call "done[0] = true;" and the other thread could check "if(!done[0])". If there is a better pattern for this please tell me.

Background of why I needed this:
In an applet, I was saving data back to the server. In order to keep the UI responsive I of course do that in a separate Thread from the Event Distpatch Thread. When I save the data I first send then data and then read the response so the user only really needs to wait for the data to be sent. Therefore I have a timer that tells the user that they don't need to continue waiting after they have waited 30 seconds. But I don't need to pop that if the response is already read so I needed a way for the reader thread to tell the timer message Runnable that it was already done. I actually found a better solution: The reader thread can call stop on the Timer so that it is never run.

No comments: