How to implement long-time tasks in Java

Source: Internet
Author: User
Tags abstract exit error handling socket thread thread class

Absrtact: In software development, we often face the problem of multithreading programming with long time tasks. In our Ezone platform development in many places involved, such as JPC Data Services JPC processing Services Alarm linkage access control system. I write a demo program in the process of a few easy manuscript, pains, but still feel that there are many places to improve, in order to reduce the risk of multithreaded programming, I translated a similar problem solution framework to achieve once and for all. For easy reading, keep the original. Please keep the author and the source of the article.

Keywords: Thread, Lock, Notification, long time task.

In an application, we often need a class to do tasks such as data processing, listening to events, or checking for activities of another class. To achieve this goal, we may use a thread with a set of locks and message notifications. The JAVA thread API is already well documented, but in order for the thread to run correctly and efficiently, programmers still need rich programming experience and a lot of code to write. By applying the framework discussed in this article, programmers can avoid suffering from the pain of writing a lot of code and quickly creating robust applications. Two, long time running the task the procedure frame.

The main thing about a long-running task is how to keep it running during the lifetime of the application. The appropriate way to implement this is to provide a thread to perform this particular task. We can achieve this goal by inheriting the thread class or by implementing the Java.lang.Runnable interface. A better object-oriented design can be achieved by implementing the Runnable interface, while avoiding single inheritance in Java. In addition, we can handle runnable instances more efficiently (for example, using a thread pool typically requires a runnable instance rather than a thread to run).

The framework is based on an abstract class called worker, which implements the Runnable interface and provides a good way to handle tasks efficiently. Some of these methods have been implemented, such as the Run () method, but some are abstract methods that developers must implement themselves. If you want to create a long-running class, you only need to inherit the worker class and implement several abstract methods. Let's look at the details of these methods.

The run () method of the Worker class is designed to continuously execute the work () method as long as the operation is not stopped. The work () method can be responsible for data processing, event response, file read and write, execute SQL commands, and so on. The work () method can throw an exception and pass the exception to run () and then handle the exceptions by the run () method.

The run () method has two layers of try-catch statements: One layer is outside the While-loop loop and one layer is inside the While-loop loop. The previous try-catch is used to catch a non programming exception to ensure that the run () method does not exit. The latter Try-catch statement captures various exceptions to the business logic and the corresponding behavior. If there is a wait operation in the work () method (for example, waiting for an input stream or a socket), it is advisable to throw a interruptedexception method. Keep in mind that as long as the application is running, the work () method does not require any while-loop loops to keep it running, all by the worker agent.

At the start of Run (), call the Prepareworker () method to prepare all the resources required for a long-running task (reference List a). For example, in this method you can open a database connection or file that you want to use. Especially for those blocking operations like setting up a socket, it's good to be here. Because if you let them run in a separate thread, the execution of the main thread is not blocked.

The opposite of the previous method is Releaseworker (), which is invoked when the run () method prepares to exit (reference list a). In this method, you can write code that frees system resources or performs other cleanup actions. The method is similar to Java.lang.Object.finalize (), but it is explicitly invoked when the thread aborts.

Iii. error-handling mechanisms in the framework

Another important method is HandleError (), which comes with a java.lang.Throwable input parameter. This method is invoked every time an error occurs on the run () method. This depends on how you implement error handling. One method is to write an error log and abort the task by calling the Halt () method (reference list a).

The Iscondition () method is used to determine whether the work () method can be executed. So fine-grained control of tasks is allowed. This is useful in the framework of event firings. When the execution condition of the work () method is not met, the work method is suspended until the condition is fully satisfied (for example, the buffer is not empty). In a worker's implementation, this condition checks a lock notification in the time period specified in Method settimeout (). If you don't need any wait blocking in a task, just make the iscondition () method always return the truth.

Iv. Timing of Mission termination

You also need IsRunning (), broadcast (), Halt () method. By accessing the IsRunning () method, you will be able to check whether a task is running and decide whether to abort it. The broadcast () method notifies the lock object correctly, and if the object waits for the lock, activates the task. The halt () method aborts a task, so that once the next isrunning () state is invoked, the run () method exits, because this method notifies only the lock that might block the thread of the task. It is advisable to use the same locks when performing blocking jobs in the work () method. If you cannot use the same lock object, such as when the Java.io.InputStream.read () method encounters blocking, you should add an explicit notification of all possible locks or increase java.lang.Thread.interrupt () to halt (). If one of your blocked objects is handled correctly, Java.lang.Thread.interrupt () will work. For example, it works when Inputstream.read () executes, but does not work with Java.sql.PreparedStatement.execute (), so you must test the halt () method under each particular condition.

Once you are familiar with the worker class, you can easily create your own implementation (reference List B), in order to run this class as a thread, simply use new Thread (new Waitedworker ()). Start. By applying thread.interrupt () or Worker.halt () or their combination, you can accurately control the execution of the task. For example, when the JVM stops by putting the appropriate code in the Java.lang.Runtime.addShutdownHook () method, you can stop all tasks.

V. Conclusion

We have examined the long running task framework and see how to create a task from creating an abstract class based on it. Its architecture is clear and flexible, and is designed to be extensible. With this framework you can avoid racking your brains for authoring classes and help you develop efficient and reliable applications.

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.