Thread security selection in Java Development and Swing

Source: Internet
Author: User
In Java Development, thread security selection and Swing-general Linux technology-Linux programming and kernel information are provided. The following is a detailed description. Swing APIs are designed to be powerful, flexible, and easy to use. In particular, we want programmers to easily create new Swing components, whether from scratch or by extending some of the components we provide.

For this purpose, Swing components are not required to support multi-threaded access. Instead, we send a request to the component and execute the request in a single thread.

This article discusses threads and Swing components. The purpose is not only to help you use the Swing API in a thread-safe way, but also to explain why we chose the current thread solution.

This article includes the following content:
Single-threaded rule: A Swing thread can only be accessed by one thread at a time. Generally, this thread is the event-dispatching thread ).

Rule exceptions: Some Operations ensure thread safety.

Event distribution: If you need to access the UI from a location other than event-handling or drawing code, you can use the invokeLater () or invokeAndWait () method of the SwingUtilities class.

Thread creation: If you need to create a thread-for example, to process jobs that consume a lot of computing power or are limited by I/O capabilities-you can use a thread tool class such as SwingWorker or Timer.

Why do we implement Swing like this: we will end this article with some background information about Swing thread security.

Swing rules:

Once the Swing component is implemented (realized), all code that may affect or depend on the component status should be executed in the event dispatching thread.

This rule may sound a little scary, but for many simple programs, you don't have to worry about thread issues. Before learning how to write Swing code, Let's define two terms: the realized and the event-dispatching thread ).

It indicates that the formed paint () method has or may be called. A Swing component that acts as a top-level window will be implemented when the following methods are called: setVisible (true), show (), or (possibly surprising) pack (). When a window is active, all components contained in it are active. Another method to make a component available is to put it into a container that has already been made available. Later, you will see some examples of current components.

The event dispatching thread is the thread that executes plotting and event processing. For example, the paint () and actionreceivmed () methods are automatically executed in the event dispatching thread. Another way to put code in the event dispatch thread is to use the invokeLater () method of the SwingUtilities class.

All codes that may affect an existing Swing component must be executed in the event dispatching thread. However, this rule has some exceptions:

Some methods are thread-safe: In the Swing API documentation, the thread-safe method is marked with the following text:

This method is thread safe, although most Swing methods are not.
(This method is thread-safe, although most Swing methods are not .)

The GUI of an application can often be built and displayed in the main thread: The following typical code is secure, as long as no (Swing or other) components are available:

Public class MyApplication
{
Public static void main (String [] args)
{
JFrame f = new JFrame ("Labels"); // set each component
// Add to the main framework ......
F. pack ();
F. show ();
// Do not do any GUI work ......
}
}

All the code shown above is run in the "main" thread. The call to f. pack () makes all components below JFrame active. This means that f. show () calls are insecure and should be executed in the event dispatching thread. Even so, as long as the program does not have a visible GUI, it is almost impossible for a JFrame or its components to receive a paint () call before f. show () returns. Because in f. after show () is called, no GUI code is available, so all GUI work is transferred from the main thread to the event dispatching thread. Therefore, the Code discussed above is actually thread-safe.

The GUI of an applet can be constructed and displayed in the init () method: existing browsers do not draw it before the init () and start () Methods of an applet are called. Therefore, it is safe to construct the GUI in the init () method of an applet, as long as you do not call the show () or setVisible (true) method for the objects in the applet.

By the way, if the applet uses the Swing component, it must be implemented as a subclass of JApplet. In addition, the component should be added to the JApplet content pane (content pane), rather than directly added to the JApplet. For any applet, you should not perform time-consuming initialization operations in the init () or start () method; instead, you should start a thread to execute time-consuming tasks.

The following JComponent methods are secure and can be called from any thread: repaint (), revalidate (), and invalidate (). The repaint () and revalidate () Methods queue requests for the event dispatching thread, and call the paint () and validate () methods respectively. The invalidate () method only marks a component and all its direct ancestor when it needs to be confirmed.

The listener list can be modified by any thread: it is always safe to call the addListenerTypeListener () and removeListenerTypeListener () methods. Adding or deleting a listener list does not affect the event distribution in progress.

Note: The important difference between revalidate () and the old validate () method is that revalidate () caches the request and combines it into a validate () call. This is similar to the repaint () cache and the Combined Drawing request.

Most of the initialized GUI work occurs naturally in the event dispatch thread. Once the GUI becomes visible, most programs are event-driven, such as button actions or mouse clicks, which are always processed in the event dispatching thread.

However, some programs always need to execute some non-event-driven GUI work after the GUI becomes visible. For example:

A program that requires long initialization before it becomes available: such programs should usually display the GUI during initialization, and then update or change the GUI. The initialization process should not be performed in the event dispatching thread; otherwise, the re-painting component and event dispatching will stop. However, after initialization, the GUI update/change should still be performed in the event dispatching thread on the grounds that the thread is secure.

Programs that must respond to non-AWT events to update the GUI: for example, imagine a server program to get requests from programs that may run on other machines. These requests may arrive at any time and cause method calls to the server in some potentially unknown threads. How can I update the GUI by calling this method? Execute the GUI update code in the event dispatching thread.

The SwingUtilities class provides two methods to help you execute code in the event dispatch thread:

InvokeLater (): Certain code must be executed in the event dispatching thread. This method returns immediately without waiting for the code to be executed.

InvokeAndWait (): The behavior is similar to invokeLater (), except that this method will wait for the code to be executed. Generally, you can use invokeLater () to replace this method.

The following are examples of using these Apis. See "BINGO example" in The Java Tutorial, especially The following classes: CardWindow, ControlPane, Player, and OverallStatusPane.


Use the invokeLater () method

You can call the invokeLater () method from any thread to request the event dispatching thread to run specific code. You must put the code to be run in the run () method of a Runnable object and set this Runnable object to the invokeLater () parameter. The invokeLater () method returns immediately without waiting for the event dispatching thread to execute the specified code. This is an example using the invokeLater () method:

Runnable doWorkRunnable = new Runnable ()
{
Public void run ()
{
DoWork ();
}
};
SwingUtilities. invokeLater (doWorkRunnable );

Use the invokeAndWait () method

The invokeAndWait () method is similar to the invokeLater () method, except that the invokeAndWait () method will be returned only when the event dispatching thread executes the specified code. If possible, use invokeLater () instead of invokeAndWait (). If you really want to use invokeAndWait (), make sure that the thread that calls invokeAndWait () does not hold any locks that other threads may need during the call.
This is an example of using invokeAndWait:

Void showHelloThereDialog () throws Exception
{
Runnable showModalDialog = new Runnable ()
{
Public void run ()
{
JOptionPane. showMessageDialog (myMainFrame, "Hello There ");
}
};
SwingUtilities. invokeAndWait (showModalDialog );
}

Similarly, assume that a thread needs to access the GUI status, such as the content of a text field, and its code may be similar to the following:

Void printTextField ()
Throws Exception {
Final String [] myStrings = new String [2];
Runnable getTextFieldText = new Runnable (){
Public void run (){
MyStrings [0] = textField0.getText ();
MyStrings [1] = textField1.getText ();
}
};
SwingUtilities. invokeAndWait (getTextFieldText );
System. out. println (myStrings [0] + "" + myStrings [1]);}

If you can avoid using threads, it is best to do so. The thread may be difficult to use and make debugging of the program more difficult. Generally, threads are unnecessary for GUI work in a strict sense, such as updating component attributes.

In any case, sometimes the thread is necessary. The following are typical cases of using threads:

Execute a time-consuming task without locking the event dispatching thread. Examples include execution of a large amount of computing, loading a large number of classes (such as initialization), and blocking the network or disk I/O.

Repeat an operation, usually at a predetermined interval between two operations.

Wait for messages from customers.

You can use two classes to help you implement the thread:

SwingWorker: Creates a background thread to perform time-consuming operations.

Timer: Creates a thread to execute or execute some code multiple times, and the user-defined latency between two executions.

Use SwingWorker class

The SwingWorker class is implemented in SwingWorker. java. This class is not included in any Java release, so you must download it separately.

The SwingWorker class does all the dirty work required to implement a background thread. Although many programs do not need background threads, background threads are still very useful when performing time-consuming operations, which can improve the program's performance.

SwingWorker's get () method. Here's an example of using SwingWorker:

To use the SwingWorker class, you must first implement a subclass of it. In the subclass, you must implement the construct () method and include your long-term operations. When you instantiate the SwingWorker subclass, SwingWorker creates a thread but does not start it. You need to call the start () method of your SwingWorker object to start the thread, and then the start () method will call your construct () method. When you need the object returned by the construct () method, you can call the get () method of the SwingWorker class. This is an example of using the SwingWorker class:

... // In the main method:
Final SwingWorker worker = new SwingWorker (){
Public Object construct (){
Return new expensiveDialogComponent ();
}
};
Worker. start ();
...
// In the Action event handling method:
JOptionPane. showMessageDialog (f, worker. get ());

When the main () method of the program calls the start () method, SwingWorker starts a new thread to instantiate ExpensiveDialogComponent. The main () method also constructs a GUI consisting of a window and a button.

When you click the button, the program will be blocked. If necessary, it will be blocked until the ExpensiveDialogComponent is created. The program then displays a mode dialog box containing ExpensiveDialogComponent. You can find the entire program in MyApplication. java.

Use Timer class

The Timer class uses an ActionListener to execute or execute one operation multiple times. You can specify the operation execution frequency when creating a timer, and you can specify the action listener of the timer action event ). After the timer is started, the actionreceivmed () method of the Action listener is called to perform the operation multiple times.

The actionreceivmed () method defined by the timer action listener is called in the event dispatch thread. This means that you do not have to use the invokeLater () method in it.

This is an example of using the Timer class to implement an animation loop:

Public class AnimatorApplicationTimer
Extends JFrame implements ActionListener {
... // Define instance variables here
Timer timer;
Public AnimatorApplicationTimer (...){
... // Create a timer
// Call the action handler object.
Timer = new Timer (delay, this );
Timer. setInitialDelay (0 );
Timer. setCoalesce (true );
...
}
Public void startAnimation (){
If (frozen ){
// Do nothing. Meet user requirements
// Stop the transformed image.
} Else {
// Start (or restart) the animation!
Timer. start ();
}
}
Public void stopAnimation (){
// Stop the animation thread.
Timer. stop ();
}
Public void actionreceivmed (ActionEvent e)
{
// Enter the next frame of animation.
FrameNumber ++;
// Display.
Repaint ();
}
...
}


Executing all user interface code in a thread has the following advantages:

Component developers do not have to have a deep understanding of Thread Programming: All components in toolkit such as ViewPoint and Trestle must fully support multi-threaded access, making expansion very difficult, especially for developers who are not proficient in thread programming. Recent sdks such as SubArctic and IFC all adopt a design similar to Swing.

Events can be distributed in a predictable order: the runnable objects in the invokeLater () queue are distributed from the same queue of the mouse and keyboard events, Timer events, and draw requests. In some toolkit that fully supports multi-thread access, component changes are interspersed into the event processing process by changing Thread Scheduling programs. This makes comprehensive testing difficult or even impossible.

Lower cost: it takes enough time and space for the Toolkit to carefully lock the critical section to manage the lock. Whenever the Toolkit calls a method that may be implemented in the Customer Code (such as any public or protected method in the public class), the toolkit will save its status and release all the locks, so that the customer code can obtain the lock when necessary. When control is handed back to the toolkit, the toolkit must re-lock it and restore it. All applications have to pay for this generation, even if most applications do not need concurrent access to the GUI.

This is the SubArctic Java Toolkit's author's description of the problem of supporting multi-threaded access in the Toolkit:

Our basic creed is that extreme care must be taken when designing and building Multithreaded Applications, especially those that include GUI components. The use of threads may be deceptive. In many cases, they are extremely simplified, making it possible to design a simple autonomous entity that focuses on a single task. In some cases, they simplify the design and coding. However, in almost all cases, they greatly increase or even become impossible to debug, test, and maintain difficulties. No matter how many programmers are trained, their experiences and practices, or the tools we use to help them, they are not able to deal with non-deterministic things. For example, a full test (which is always difficult) is almost impossible when a bug depends on time. Especially for Java, a program runs on the operating system platform of many different types of machines, and each program must work properly under preemptive and preemptive scheduling.

Due to these inherent difficulties, we advise you to think twice whether there is absolutely a need to use threads. Even so, in some cases it is necessary to use threads (or imposed by other software packages), subArctic provides a thread-safe access mechanism. This chapter discusses the mechanism and how to operate the interaction tree securely in an independent thread.

The thread security mechanism they call is very similar to the invokeLater () and invokeAndWait () methods provided by the SwingUtilities class.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.