技术开发 频道

Active Object并发模式在Java 中的应用

  实现 Method Request,如清单 3 所示:

  清单 3. Method_Request

                        
class Method_Request {
public:
    
// Evaluate the synchronization constraint.
    virtual bool can_run ()
const = 0
    
// Execute the method.
    virtual void
call () = 0;
};
// Inherites from Method_Request
class
Get : public Method_Request {
public:
    
Get (MQ_Servant *rep, const Message_Future &f)
    :servant_ (rep),
    result_ (f)
    {
    }
    virtual bool can_run ()
const {
        
// Synchronization constraint: cannot call a
        
// <get> method until queue is not empty.
        return !servant_
->empty ();
    }

    virtual void
call () {
        
// Bind dequeued message to the future result.
        result_
= servant_->get ();
    }
private:
    MQ_Servant
*servant_;
    Message_Future result_;
};

  实现 Activation List,如清单 4 所示:

  清单 4. Activation_List

class Activation_List {
public:
    
// Block for an "infinite" amount of time waiting
    
// for <insert> and <remove> methods to complete.
    enum { INFINITE
= -1 };

    
// Define a "trait".
    typedef Activation_List_Iterator iterator;

    Activation_List ();

    
// Insert <method_request> into the list, waiting up
    
// to <timeout> amount of time for space to become
    
// available in the queue. Throws the <System_Ex>
    
// exception if <timeout> expires.
    void insert (Method_Request
*method_request,Time_Value *timeout = 0);

    
// Remove <method_request> from the list, waiting up
    
// to <timeout> amount of time for a <method_request>
    
// to be inserted into the list. Throws the
    
// <System_Ex> exception if <timeout> expires.
    void remove (Method_Request
*&method_request, Time_Value *timeout = 0);

private:
    
// Synchronization mechanisms, e.g., condition
    
// variables and mutexes, and the queue implementation,
        
// e.g., an array or a linked list, go here.
};

  Activation List 的实际上就是一个线程同步机制保护下的 Method Request 队列,对该队列的所有操作 (insert/remove) 都应该是线程安全的。从本质上讲,Activation List 所基于的就是典型的生产者 / 消费者并发编程模型,调用者线程作为生产者把 Method Request 放入该队列,Active Object 线程作为消费者从该队列拿出 Method Request, 并执行。

0
相关文章