Applied long-running Active Object Pattern

Source: Internet
Author: User
  • Download
    Source-462.66 KB
Introduction

Once I Came authentication ss the problem of uploading a file from a client's application to the application server. file sizes can vary and the situation where the service cocould reject the file because it exceeds the maximum size of data may occur or cause a timeout.
Client's application was to remain responsive to other high priority events, such as processing events of the application server, rendering the user interface, Etc ., while carrying out a long-running Upload File task. the task needed to be canceled before
Completion to show the progress of the completion of the task. It was important for the transfer to continue from the place where an error occurred rather than from the very beginning.

Figure 1. An example of solving such problems in a well-known application. Problem

A process needs to carry out a long-running task (a task, with an unpredictable duration) while remaining responsive to high priority events. the task shoshould be split into smaller subtasks. the task at any time can be interrupted or susponded and then resumed.

Solution

Long-running Active Object pattern is the best solution for solving this one and other
Similar Tasks.

Structure

Active objects are very similar to traditional (passive) objects. They have private fields and provide methods to operate on this data (figure 2 ).

Figure 2. passive object.

The only vivid distinction lies in the fact that each active object runs in its own thread of control and the invoked methods do not block the client (caller) but are executed asynchronously. active objects have public interface and internal implementation.
Public interface is often called proxy. it is available for the client and is responsible for accepting method calland it has the ideally same interface as passive object. the proxy transforms the method callinto messages and puts them in a queue (Message
Queue) and asynchronously returns possible results in the form of future objects. the message contains all the necessary information to perform the method, task priority and so on. A special object usually called dispatcher or scheduler dequeues and processes
Each incoming message from the queue according to a participant algorithm and then invokes the actual methods of the servant. the servant is the real method itself for implementation or in other words a passive object method that was used until the active objects
Pattern was applied. active objects are inherently thread-safe by sequentially dequeuing and processing enqueued requests and always executing servant's methods in a single thread of control. the thread-Safety of active objects largely removes the need
Manual locking and mutual exclusion mechanisms (Figure 3 ).

Figure 3. Active Object.

Client can try to get the result of the future object at any moment. if the result has not yet been calculated, the client will be forced to suspend the execution and await the result of the execution of an active object. alternatively there might be
A case when the execution of the active object led to an error. in this case, the future object will enter the error state and will get the full information about occurred exception. the client may try to cancel the execution of the method. if this happens
Before the message has been processed, the dispatcher will cancel the servant's method and will set the state of the future object as canceled. Possible states of the future object are shown in figure 4.

Figure 4. Future object states. Dynamics

There must be a dispatcher or scheduler created before proceeding any work with an active object. dispatcher requires an algorithm (Strategy) to obtain the next message from the queue. this algorithm can be set either before or during the launch dispatcher.
Dispatcher, together with the proxy implements the producer-consumer pattern. dispatcher shares with the proxy a common message queue and processes the incoming messages. dispatcher can be suincluded and then resumed. figure 5 shows the activity dimo-of
The dispatcher.

Figure 5. Activity divisor of the dispatcher.

If one or more messages get in the queue, the dispatcher starts the working thread (workflow) to process them. if no messages are in the queue, the working thread stays in standby mode. dispatcher, according to the selected algorithm, es the first
Message from the queue and invokes itsAllowInvoke()Method.
This method can allow or deny the execution of the method of the servant. thus, the security mechanism (guard) is implemented for the Safe invoke of the servant. if it is not possible to process the message at the moment, the dispatcher gets the next one from
The queue. If the guard allows the execution, dispatcher invokes the MethodInvoke()Of
The message. In case of error execution, other methodFailed()Will
Be applied and future object will be set toHasFailedState.
In case of successful execution, the dispatcher sets the state of the future objectHasSuccessedAnd
The future objects will assign the result of execution of the MethodInvoke().
It is also possible that the client can cancel the processing of the message (Cancelled).
Once the dispatcher is installed, we can perform the methods of the active objects.

Using the code

The following classes have been developed to solve a particle problem, which is to upload a file of an indeterminate size to the Application Service in the background with the ability to cancel the operation:
ProcessFileByPiecesCommandIs
A servant, which implementsIServantInterface.
The main objective of this class is to divide a file into equal parts and to read them continuously. the next message is created by proxy and is added to the Message Queue automatically after the servant has been sent the previous piece of file to the application
Service (this implementation is omitted in this example ). this process occurs until all parts of the file are fully read and sent or the process aborts due to the abolition of the user or when an error occurs.
ActiveObjectProxyServantIs
A class-adapter to work with the objects that implement the interfaceIServant,
As with the active objects. implementation of the proxy is absent in its pure form. we can use dynamic proxy by Castle project or other frameworks to create proxies. this adapter can be invoked by proxy. the same adapter can be used to copy another file,
Second, third and so on. Thus, the adapter has a list of future objects to hold all final and intermediate results for every method call.
ActiveSchedulerIs
A dispatcher to process messages. dispatcher can execute other active objects 'messages of the system. for example, the task of uploading the file has a low priority, so if there is a new message with higher priority in the queue, it will be processed by
Dispatcher On The first place. Thus the dispatcher will handle the critical tasks firstly and only then the low priority ones.
PriorityAndLIFOIs
A class that implements InterfaceIQueueSortStrategy.
It sorts the messages according to their priority and consecutive number in the queue.
FutureAnd
Its descendants are designed for storing the state and the results of the execution of the method of the active object.
ServantOperationIs
A message (IOperation,Operation).
It contains information about operation, its priority and the reference to the future object. Dynamics of the active object are shown in Figure 6:

Figure 6. Activity digoal of the active object to upload the file to the application server. points of interest

There were other design patterns ratherActive
Object
Used during the implementation. They are:Strategy,Factory
method
,"Fail
First"
(Assert, assertion ),Command,
AndProxy.
During the development, the following. NET Framework features were used, in participates version 3.5: Reflection, custom attributes, Operator overloading, multithreading, locks (ReaderWriterLockSlim,Monitor),
And of course, powerful object-oriented programming was present. Also the attributes of any good code were used, such as unit tests (nunit) and Code documentation.

License

This article, along with any associated source code and files, is licensed under
Code project open license (cpol)

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.