Java technology: allows you to easily program multi-threaded applications (2)
Source: Internet
Author: User
Java technology: enables you to easily program multi-threaded applications (2)-Linux general technology-Linux programming and kernel information. For more information, see the following. Wait () and notify () mechanisms are used to complete "Sleep" and "kicking ". The actual consumer work is handled by the OnConsume (Object) method, as shown in listing 3:
Listing 3. Wakeup and notification Consumer
/**
* Add an object to the Consumer.
* This is the entry point for the producer.
* After the item is added, the Consumer's thread
* Will be notified.
*
* @ Param the object to be 'sumed' by this consumer
*/
Public void add (Object o)
{
_ Queue. add (o );
KickThread ();
}
/**
* Wake up the thread (without adding new stuff to consume)
*
*/
Public void kickThread ()
{
If (! This. _ thread. isInterrupted ())
{
Synchronized (_ waitForJobsMonitor)
{
_ WaitForJobsMonitor. Policy ();
}
}
}
Example: MessagesProcessor
To show you how the Consumer class works, we will use a simple example. The MessagesProcessor class processes incoming messages asynchronously (that is, it does not interfere with the call thread ). It works to print a message when it comes. MessagesProcessor has an internal Consumer that processes the incoming message job. When a new job enters an empty queue, Consumer calls the processMessage (String) method to process it, as shown in Listing 4:
Listing 4. MessagesProcessor class
Class MessagesProcessor
{
String _ name;
// Anonymous inner class that supplies the consumer
// Capabilities for the MessagesProcessor
Private Consumer _ consumer = new Consumer ()
{
// That method is called on each event retrieved
Protected void onConsume (Object o)
{
If (! (O instanceof String ))
{
System. out. println ("illegal use, ignoring ");
Return;
}
MessagesProcesser. this. processMessage (String) o );
}
}. SetName ("MessagesProcessor"). init ();
Public void gotMessageEvent (String s)
{
_ Consumer. add (s );
}
Private void processMessage (String s)
{
System. out. println (_ name + "processed message:" + s );
}
Private void terminate ()
{
_ Consumer. terminateWait ();
_ Name = null;
}
MessagesProcessor ()
{
_ Name = "Example Consumer ";
}
}
As you can see from the code above, it is quite simple to customize a Consumer. We use an anonymous internal class to inherit the Consumer class and overload the abstract method onConsume (). Therefore, in our example, we only need to call processMessage.
Advanced features of the Consumer class
In addition to the basic requirements raised at the beginning, we also provide some advanced features that we find useful for the Consumer class.
Event Notification
OnThreadTerminate (): This method is called only before the Consumer is terminated. We covered this method for debugging purposes.
GoingToRest (): This method is called only before the Consumer thread enters sleep (that is, it is called only before _ waitForJobsMonitor. wait ). This notification may be required only when the consumer needs to process a batch of processed tasks before entering sleep.
Termination
Terminate (): the asynchronous termination of the Consumer thread.
TerminateWait (): sets the call thread to wait until the consumer thread is actually terminated.
In our example, if we use terminate () instead of terminateWait (), the problem will occur because the onConsume () method is called after _ name is set to a null value. This will cause the thread executing processMessage to throw an NullPointerException.
Conclusion: benefits of the Consumer class
You can download the source code of the Consumer class in the references section. Please use the source code freely and expand it as needed. We found that using this class for multi-threaded application development has many advantages:
Code reuse/deduplication: If you have a Consumer class, you do not have to write a new Consumer for each instance in your application. If the producer-consumer solution is frequently used in application development, this can greatly save time. In addition, remember that repeated code is a fertile ground for generating errors. It also makes the maintenance of basic code more difficult.
Fewer errors: using verified code is a good practice to prevent errors, especially when dealing with multi-threaded applications. Because the Consumer class has been debugged, it is safer. The consumer also acts as a security intermediary between the online and resources to prevent thread-related errors. Consumers can access resources in sequence on behalf of other threads.
Beautiful and clear code: using the Consumer class helps us compile simpler code, which is easier to understand and maintain. If we do not use the Consumer class, we must write code to process two different features: the consumption logic (queue and thread management, synchronization, etc.) and the code that specifies the usage or function of the Consumer.
Thanks to Jonathan Lifton and Dov Trietsch of Allot Communications for their help in this article.
References
Click the Forum at the top or bottom of this article to participate in this article.
Download the source code of the Consumer class. Please use this source code freely and expand it as needed.
Alex Roetter's "Writing multithreaded Java applications" (developerWorks, February 2001) provides a good introduction to using the "Java thread API" to develop multi-threaded applications.
Brian Goetz's three-part multi-thread series (developerWorks, July 2001-September 2001) provides practical solutions to certain public issues arising from multi-threaded application development. Read the entire series of articles:
Part 2: "synchronization is not an enemy"
Part 1: "reducing competition"
Part 2: "Sometimes it is best not to share"
If Allen Holub is king, the Java language will undergo many important changes in its support for multithreading. For more information about these changes, see his proposal to modify the Java thread model (developerWorks, October 2000 ).
Eric Allen's column "Diagnosing Java Code: The Orphaned Thread bug pattern" (developerWorks, August 2001) provides tips for multi-threaded Code debugging. Note that Eric uses the producer-consumer solution in his example.
Java Developer Connection provides a valuable clue to those who conduct thread synchronization research. A key example uses the producer-consumer solution.
How to support scheduled events in Java applications? To facilitate implementation of this task, Sun Microsystems introduced a new Timer API in JDK 1.3.
The Java Developer Connection article "An Introduction to Java Stack Traces" shows you how to identify and collect clues in Stack tracing to solve your Java software problems.
IBM Developer Kit for Linux, Java technology edition, and version 1.3 provide complete support for multi-threaded application development.
In the developerWorks Java technology area, you can find hundreds of articles on every aspect of Java programming.
About the author
Joseph (Saffi) Hartal is a software developer for GlobaLoop LTD. Saffi has a bachelor's degree in computer science and mathematics from Tel-Aviv University and a master's degree in business administration. He has been engaged in software development for the past 10 years. During this period, he wrote real-time embedded code in C ++ and Java client and server applications. Saffi spent most of its time writing infrastructure code and solving problems. You can contact him through the saffi@myrealbox.com.
Ze'ev Bubis is the owner of a software development team in GlobaLoop LTD. Ze'ev has a bachelor's degree in computer science and mathematics from Tel-Aviv University. He has been engaged in software development for the past 10 years, during which he has compiled software applications for multiple platforms and languages. In the last three years, ze'ev has focused on developing client and server applications in Java. You can contact him through the zeevb@myrealbox.com.
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