Java event handling model (transfer)

author: banq

Source: JDON.COM

Java event model is an important basis for dynamic response system in the field of graphical user interface event model has been introduced many articles, but in the server side we will encounter more of the incident mode, where I tried to sum up:

A direct drive mode <br /> event patterns, the first requirement is performance requirements, the need directly and quickly, Command pattern is to be frequently used, mainly for the expeditious processing of the command front, Command pattern is often an important part of the system architecture is also the main mode of flow control.

Command mode Reflect often used in conjunction with Java, because the system's event handling system is in dynamic change, with the functional requirements of expansion, there may be dynamic event handling response system in order to Struts in action, for example, we know that, Structs, a The main configuration file is struts-config.xml is as follows:

 <struts  -config >
 <action  -mappings >
 <action path  ="/login" type="com.javapro.struts.LoginAction"/ >
 <action path  ="/logout" type="com.javapro.struts.LogoutAction"/ >
 <  /action- mappings >
 <  /struts-config >

It is actually a command and event mapping, through the configuration file, run-time dynamically load the corresponding Action, complete the Command mode, we check LoginAction code, you can see the Command mode of the basic features:

public final class LoginAction extends Action {
 public ActionForward execute  (ActionMapping mapping,
 ActionForm form  , HttpServletRequest request, HttpServletResponse response)
 throws Exception  {

Obviously, the typical model of the need for an interface Command. Interface, there is a unified approach, where a unified approach is to execute;

For instance, we have a real-time systems, the customer segment to the server code in different codes, which means different requests, different requests have different Handler for processing, Handler interface is:

public class Handler{

 public byte  [] handleRequest();


The process of succession of different nature this Handler interface, such as those for processing into the system:

public class EnterHandler implements Handler{

 public byte  [] handleRequest(){
    // Specific business processes


Handler called when:

// From the cache Gets the requestId corresponding Handler
Handler handler = (Handler)cache.get(new Integer(reqId));
// Calls handleRequest method handler of the consolidated  ()
byte[] outInf = handler.handleRequest();

These are commonly used in an event-driven model. It is characterized by an event to start the corresponding event handler directly.

Chain of Responsibility Chain of Responsibility should also fall into this category, when the event arrived, let this event we provide a number of processors one by one to select the appropriate processor for processing, this model is obvious shortcomings, the performance lost in one by one to select on, is generally not recommended to use, this model suitable for the events that we can not predict the content to use, because they do not know the specific circumstances of the events, we can not run the program prior to their pre-assigned to the corresponding processor, can only rely on run When the event themselves to explore "clash of luck."

Monitor Type Event Mode

Monitor type event model is different from the incident on the direct-drive mode, it is through a third party to monitor and trigger events, such events are characterized by: There is a periodic independent observer stay out of the running, we will be the event we have to listen to the The observers registered, so that the observer instead of us to listen to this event, the application client to get the event through the observer status.

Application clients there are three ways to interact with the observer: 1. The direct integration of two. Push mode 3. La mode.

Direct integration means that application of the client himself is an observer, the two fusion, this would no doubt use the client access to the trigger time is the fastest.

Push way to the observer, once the incident is detected, immediately Push push the incident to the application client; pull a similar way to collect items, the application client when needed pull events from the observer.

JDK 1.4 for None Blocking I / O is a typical monitor-style event model implementation, Selector is obviously a monitor I / O, a third party, when there are external events come in, by calling the ways to get external events to be processed , refer to my column article.

Monitor type event model suitable for use in triggering the nature of the occasion, such as a database back-end interface to trigger the trigger I / O triggering state change trigger and so on.

We trigger a letter, for example, is actually a Observer Application examples:

For example the user draws a data server computing, if the user requests the same time, the calculation results to their own hair a mailbox, then we look at how to design? As a general rule of thinking, this is a sequence, starting with the calculation of data in memory and then send the results to his mailbox, finally returns the results to the client, we know that sending the letter is time-consuming and, therefore, possible reasons for the network caused by very slow to send the letter, which the user can not wait until he has been calculated results, it is clear that we use the monitor-style event model to solve, so that the events written by the monitor to complete, as long as necessary, can be triggered by:

public class Computer extends Observable{

 public Computer  (){
      // The sendMailObserver is set to this category of the observer.
 addObserver  (new sendMailObserver());


 public void compute  (String input,boolean needEmail,String email){

      // Computing operation

 if  (needEmail){

        // Settings change point
 setChanged  ();
        // If you need to send an email, we put the email address as an argument in the past
 notifyObservers  (email);



Let us look at how to monitor the observer code is written in?

public class sendMailObserver implements Observer{

 public void update  (Observable obj,Object email){

 if  (email instanceof String){

 sendMail  (email);




This server implementation of the compute method, there is no waiting to send e-mail, a direct continuation of the implementation.

Monitor-type event patterns and event-driven model can be directly used together in one system, the outside world through a direct drive mode the signal to start the system processing module, the system processing module processing, you can monitor the style event model to trigger the other background tasks. Such a structure is very suitable for real-time processing system.

Since the event handling model is one of many applications, the basic model, it should be able to form a framework for standards, JMX's notification Model is one such architecture.

JMX Notification Model

We know that, JMX is to provide an MBean resources for the implementation of the control and configuration management mechanisms, but this is a complex, distributed as part of the system, there is need for resources is capable of sensing changes in a particular event or state change of mechanism, which is the JMX Notification Model. In the JMX Notification Model can be achieved in both the "incident direct-drive mode" and "monitor-style event mode", depending on your application requirements.

JMX Notification Model allows MBean broadcasting notifications by calling the event, as long as the recipient is registered as a listerner, JMX The MBean notification model will be activated this listerner register once, and then receive from the broadcaster has been issued by the events.

Event Mode has three roles, the first one is the event producer and then the event sender recipient Consumer, the third is to transfer events. JMX notification model is also the case were to rely on the following components to achieve these three roles:

A. NotificationBroadcaster interface, event broadcasting sender, this interface allows listeners in the need to send a notification to register their interest in events.

B. General Event (Notification), which we want to transfer events. Notification events can be used directly, but also can become a sub-classes, which are dependent on information transmitted along with the event. Through the use of common event types, listeners will be able to receive from broadcasters of all types of events.

C. NotificationListener interface, event listener, or receiver, for receiving any notification from the signals of broadcasters.

D. NotificationFilter interface, this interface is listener notification issued to provide an event filter.

E. NotificationEmitter interface, extends the NotificationBroadcaster interface, remove the listener when the time to allow more control functions.

As long as MBean, a notification on the release of both broadcasters, you can also become a recipient of notification of the listener, or at the same time either.

Attribute Change Notifications

Attribute Change Notifications is a special kind of notification, at any time MBean attributes attribute is modified, the outside world can be notified.

In the JMX architecture, MBean able to attribute changes in the property occurs, issued a notice on the diagnostic properties and triggering mechanisms of the changes is not a JMX notification event the provisions of section, each MBean implementation can have its own independent way.

Timer Service

Timer Service trigger is at the specified date and event notification, it can be a constant gap 11 repeated notice, notification can be sent to all registered as a timer notification object, Timer Service is a managed MBean, allow the application the system can be configured to set up a scheduling level.


Through the use of monitoring service, one or more MBean attributes will be provided time interval being monitored, as far as observation Mbean, monitors from the monitor on it to get a value, called the derived gauge, the derived gauge can be observed properties of the original value, can also be a number of attributes the difference between consecutive values was observed.

When the derived gauge value is to meet a series of conditions, each monitor server will issue a particular type of notice. These conditions are set when the monitor is initialized, you can also monitor MBean's management interface through dynamic setting.

According to the internal MBean attribute value types are three kinds of monitor:

A. CounterMonitor - the use of Java, to observe the properties of integer type, there is a behavior:

a. is always greater than or equal to zero.

b. be able to auto-increment.

c. can be rolled back.

B. GaugeMonitor - the use of java observation of integer or floating-point type properties. Like gauge (measuring instruments) either increased or decreased less.

C StringMonitor - use the String type observed properties.

Event Processing Architecture

JMS is based on Socket A messaging framework, principles similar to the control-type event model, but this model JMS has already risen to the height of structure. There is also a different JVM on JMS messages can be achieved event systems (note the system, not simply a small incident of) the trigger and activation.

Java event handling model (transfer)

JMS architecture diagram from the above events can be seen that the role of Producer and Consumer, as well as three event information itself Message. JMS is Producer and Consumer to establish a connection between the Connection.

JMS enables synchronous or asynchronous events trigger mechanism, namely through the Poin to Point (pull mode), and Pubilsh / Subscibe (push method) concrete to complete, in a distributed computing environment, the asynchronous mechanism is very important, can play a decoupling role, as a single point in the distribution environment, errors or communication problems often occur, the entire distributed system can not always rely on synchronization mechanism to reliably deliver an event or notification.

Thus, Java event handling model from a number of infrastructure to our specific application, can be seen everywhere, depending on the application needs to select a different event handling model, can truly tap the potential performance of Java.

分类:Java 时间:2010-03-29 人气:422
blog comments powered by Disqus


  • Windows and Linux systems in the dynamic library 2010-11-08

    (Rpm) Of: Liu Shidong Yang Lin 1 Introduction Dynamic libraries (Dynamic Link Library abbr, DLL) technique is often used in programming technology. The aim to reduce the size of the program, save space, improve efficiency, with high flexibility. Dyna

  • Linux kernel flow control (6) 2011-01-10

    This document Copyleft owned yfydz all use under the GPL, can be freely copied, reproduced, reprinted, please maintain the integrity of the document, for any commercial purposes is strictly prohibited. msn: Source: http://yfydz.

  • The Ubuntu Server in VMware build Java server environment (LAMT architecture) 2010-05-12

    (Connected to 1) Identified the installation of Linux strategy, then the following on my surgeon practices in a VMware Ubuntu Server-based Java server based experimental environment, I like to call LAMT architecture: Linux + Apache + MySQL + Tomcat.

  • Linux kernel flow control (3) 2011-01-10

    This document Copyleft owned yfydz all use under the GPL, can be freely copied, reproduced, reprinted, please maintain the integrity of the document, Be used for any commercial purposes is strictly prohibited. msn: Source: http:

  • Shell Learning (5) flow control 2011-06-03

    Flow Control Bash Shell, the flow control command has two categories: selection and circulation. There are choices: if, case; there are loops: for, while, until; command to select both options are also part of cycle. Either way, the conditions requir

  • Efficient Java exception handling framework (change) 2010-09-26

    Abstract: This article from the most basic concepts of Java exceptions, the syntax of the Java exception handling began to talk about the basic knowledge of the Java exception architecture, compared to Spring's exception handling framework, expounds

  • Linux kernel flow control (2) 2011-01-10

    This document Copyleft owned yfydz all use under the GPL, can be freely copied, reproduced, reprinted, please maintain the integrity of the document, Be used for any commercial purposes is strictly prohibited. msn: Source: http:

  • Linux kernel flow control (9) 2011-01-10

    This document Copyleft owned yfydz all use under the GPL, can be freely copied, reproduced, reprinted, please maintain the integrity of the document, for any commercial purposes is strictly prohibited. msn: Source: http://yfydz.

  • c # learning notes (b) Boolean logic, flow control 2010-04-07

    Boolean logic Flow Control goto, for, switch, while, do ... while statement, similar to java The only note that, java in c # foreach loop with distinct forecach ----- java version for (String string: args) () foreach - c # version foreach (String age

  • JavaScript Flow Control Chapter 2010-05-03

    Unary bitwise logical operator Multiplicative operator Additive operator of relational operators such as assignment operator operator conditional operator comma operator if statement loop switch statement break statement continue statement if stateme

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 0.248 (s). 12 q(s)