Programming | multithreading | network
SummaryThis paper introduces and analyzes the Universal Network Connection Framework (GCF) of J2ME, and on this basis, points out the problems existing in the programming of J2ME network connection, and puts forward two ways to solve the problem by constructing multithreading.
Key WordsJ2ME GCF Multi-threaded Network connection
Introduction
J2ME (Java 2 Micro Edition) is an integral part of Java 2, and it is called J2SE, EE. J2ME is a highly optimized Java operating environment, mainly for consumer electronics, such as cellular telephones, videophone, digital set-top boxes, and car navigation systems. The J2ME is a Java-specific version tailored for consumer electronics and handheld devices.
The advent of J2ME has made it possible to develop applications for Cross-platform consumer electronic products. Platform-Independent features of the Java language are ported to small electronic devices to allow shared applications between mobile wireless devices. It provides an advanced Internet protocol based on HTTP that enables mobile phones to access all the information directly to the Internet in a client/server manner, allowing different client access to different resources.
In the future wireless communication era, a large number of network applications will be developed to meet the requirements of wireless mobile communication, but to fully play the wireless mobile communication equipment communication capabilities, J2ME network programming has become particularly important. So in order to efficiently network programming, you need to take advantage of the Java language Multithreaded programming mechanism.
1, J2ME Network Connection Framework (GCF)
The Universal Connection Framework (Generic Connection FRAMEWORK,GCF) provides an extensible, common I/O framework for resource-limited devices. GCF is a set of interfaces defined in the Javax.microedition.io package. Figure 1 shows the class hierarchy of the GCF.
Figure 1 class hierarchy of GCF
There are seven interfaces defined in GCF, where Connection is the most basic type of connection. It also provides support for packet and stream connections. The interfaces that provide more functionality are derived down the hierarchy. For example, the Streamconnection interface supports both input and output streams, and the Contentconnection interface extends the Streamconnection interface to support the determination of the content type, data length, and encoding format of the convection. The Httpconnection interface extends the Contentconnection interface to support standard HTTP requests. A Mobile Information device framework, as defined in the framework layer for mobile or two-way pagers, in its MIDP 1.0 specification only requires the device to support the HTTP connection protocol, while the updated MIDP 2.0 specification requires simultaneous support for the information HTTP and HTTPS, which provides support for more secure network connections.
2. Multithreading in Network programming
Because the target device has a small memory, low computational power and battery power, so how to make applications run efficiently is a big problem in development. Especially for mobile information devices such as mobile phones, the characteristics of wireless communication for our program put forward higher requirements. From the point of view of code optimization, It is very important to introduce multithreading in network programming.
When the program is running, the application Management Software (Application management software) First Initializes a midlet, and then calls its Startapp () method to make the midlet into the active state, which is the main thread, the program branch. It performs other methods and then returns to this branch to continue execution. However, a network connection is a potentially clogged operation, meaning it may not return for long periods of time.
While simulating a segment of the network connection program running in Sun's wireless development Kit WTK, WTK prompts the network connection to work to plug user input and create another thread for networking. For the above situation, the introduction of multithreading processing mechanism.
2.1 Using Thread class and Runnable interface
When you write a J2ME network-connected application, you often use the command display widget to invoke its event handler function to complete the network connection work, the code framework is as follows:
public void Commandaction (Command C, displayable s) {
if (C==sendcommand) {
Requestconnect ();//Connection method
}
else if (
C==backcommand) {
Display.setcurrent (MainForm); }
else{
Destroyapp (FALSE);
Notifydestroyed (); }
}
To get an HTTP connection
private void Requestconnect () {
String url= URL. URLString
Httpconnection HPC = null;
try{
HPC = (httpconnection) connector.open (URL);
int status = Hpc.getresponsecode ();
if (Status!= HTTPCONNECTION.HTTP_OK)
Content = "failed online!";
Else
Content = "Online!";
}
catch (IOException e) {System.out.println (content);}
try{
if (HPC!= null) hpc.close ();
}
catch (IOException E2) {}}
The procedure above can be expressed in fig. 2 Working principle diagram A.
Fig. 2 Working principle diagram a
As you can see in Figure 2, if such a network connection program is running on a mobile phone, it may not be able to get a response for a long time. Because the connection work has only one main thread, all applications are carried out in this main thread, if this main thread does not return, then the behavior can not be followed, the user can not do any action.
The following improves the program to create a Connectpipe class that implements the Runnable interface to create multithreading. The code is as follows:
Implement Runnable interface
Class Connectpipe Implement runnable{
......
public void Run () {
Requestconnect ();}
}
To modify the Commandaction function:
public void Commandaction (Command C, displayable s) {
if (C==sendcommand) {
Create a new thread
New Thread (New Connectpipe ()). Start ();
}
else if (C==backcommand) {
......
}
}
After modification, the program can run more smoothly, when the network connection is processed, the main thread will return immediately after the start of the threads, two threads in parallel, will not cause congestion in this place. Its working principle can be expressed in fig. 3 Working principle diagram B.
Fig. 3 Working principle Diagram B
Detailed analysis of Figure 3, and found that although the program can work correctly, but each time the user presses the button will have a new thread generation, which is obviously not efficient, and asynchronous behavior may cause a deadlock between two threads. Fortunately, wait () and notify ()/notifyall () are provided in Java to communicate between threads, and to reconcile synchronization problems. Then the thread synchronization problem in this program, the design idea is as follows: After starting the thread, let it enter the state of waiting, when the user activates the command event to wake the thread, so that it continues to run. The code resembles the following:
Public synchronized void Run () {
while (dealing) {
try {wait ();} Thread wait
catch (Interruptedexception IE) {}
if (dealing) requestconnect ();
}
}
Public synchronized void Deal () {
Notify ()//Wake thread
}
Where the dealing variable is used to define a lock, when true, the current thread waits until the user activates the command event, invoking the Notify () in the deal () method to wake the current thread to continue running. This program appears to be quite efficient and avoids the deadlock between threads to a large extent. Its working principle can be expressed in fig. 4 Working principle diagram C.
Fig. 4 Working principle Diagram C
2.2 Using System class timer and TimerTask
The System class Timer class is a timer, combined with the TimerTask class to implement a specific task in MIDlet. It should be explained that each timer object is actually a separate thread running in the background. This is because the tasks that are scheduled once are owned by the implementation object of the TimerTask class, the TimerTask class is an abstract class, and its main feature is the implementation of the Runnable interface, thus extending the public void run () method that must be implemented.
Therefore, in the J2ME network programming, we can use the Timer class and TimerTask class to establish the thread, completes the network connection and so on work. Design idea is as follows: Create a Timer class timer, a TimerTask class that completes the network connection function, when the system is idle, the repetitive dispatch task requests the connection, until the connection succeeds, then calls the TimerTask class's Cancel () may stop a specific dispatch task. The core code resembles the following:
Class Connecttimer Implement timertask{
Connecttimer () {
M_timer = new timer ();//define Timer
M_timer.schedule (this,500,5000); scheduling tasks
}
......
Public synchronized void Run () {
Requestconnect ();//Connection method
Cancel ()//Canceling task
}
}
public void Commandaction (Command C, displayable s) {
if (C==sendcommand) {
New Connecttimer;}
else if (C==backcommand) {
......
}
}
3. Concluding remarks
To sum up, in the J2ME application development of network program design has an important position, and the key to programming is to write efficient and friendly J2ME network connection program. Through the multithread processing mechanism built in Java language, synchronous parallel processing is done by thread, which solves the problem of blocking in network connection, and achieves the goal of efficient program operation.