28.12.2012 Views

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

152 Chapter 2 Frames, Labels, and Buttons<br />

look-and-feel can be rendered. The paint method is almost never invoked<br />

directly by application code—usually, it is called as a result of the component<br />

being made visible or being exposed after being covered by another window<br />

that is subsequently moved to reveal it. These user interface events cause the<br />

windowing system to deliver an internal event which is translated to an event<br />

in the <strong>Java</strong> virtual machine and then placed in the AWT event queue and processed<br />

by the event thread. In other words, when a component draws itself in<br />

its paint method, it is executing code in the AWT event thread. As a result,<br />

therefore, all Swing applications are multi-threaded, even the simple one<br />

shown in Listing 2-6.<br />

Armed with this knowledge, you should now be able to see why there is a<br />

possible thread-safety issue with the example code that we have been looking<br />

at. When the fourth button is added to the window and the window is<br />

resized, the code that performs these actions is running in the virtual<br />

machine's main thread. What happens if, at exactly the same time, the user<br />

does something that will require the window to repaint itself, such as hiding<br />

the main window and then exposing it, thus causing a paint event to be<br />

placed into the AWT event queue? Theoretically, there is a small chance that<br />

the event thread could dispatch this event and start painting the applications<br />

main window at exactly the same time as the main thread is changing the<br />

windows layout. Figure 2-24 shows a possible sequence of actions that<br />

clearly shows the multithreading aspect of this apparently simple example.<br />

Figure 2-24 Potential multithreading conflicts in a Swing application.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!