Multithreading and the User Interface

If you have developed J2SE GUI applications with Swing, you know that you have to be very careful when manipulating Swing components, because, with the exception of a few special cases, they are not thread-safe. The end result of this is that, although the application may be multithreaded, any logic that affects the user interface must be executed in the event thread. The MIDP user interface components, however, are completely thread-safe, so you can create and manipulate them from any thread. This makes writing MIDlets much simpler than building Swing applications. Nevertheless, there are a few things that you need to be aware of with regard to multithreaded MIDlets. We’ll cover those in this section.

Serialization of User Interface Events

Although application code can freely access user interface components from arbitrary threads, the user interface code itself arranges for all of its own event handling to be serialized. Thus, only one of the following may be happening at any given time:

  • Painting of any user interface component by calling its paint( ) method

  • Reporting of a key event in the Canvas keyPressed( ), keyRepeated( ), or keyReleased( ) methods

  • Reporting of pointer events in the pointerPressed( ), pointerDragged( ), and pointerReleased( ) methods

This serialization is achieved by running all these methods in a single thread, which we’ll refer to here as the event thread. From the MIDlet point of view, this can be a great benefit, ...

Get J2ME in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.