Concurrency Pattern: Active object pattern
Tushar Goel
Lead Member Of Technical Staff @ Salesforce | Staff Software Engineer, Technical Lead
This pattern is a type of concurrency design pattern and widely used in applications. Also, it is used to create concurrent APIs like ExecutorService in Java.
If we go in the past maybe a decade, if we have to upload a file in Yahoo email or Gmail then we have to wait till the file is uploaded before moving to any other work. Your screen was locked till the moment the file was uploading. Why it has happened? Bec of Single thread. Your email was running on a single thread which blocks all other requests till uploading completed.
But if we compare it now, we can do multiple tasks simultaneously. How does it happen?
Thanks to the Active Object pattern which actually helps to overcome this issue. How does this pattern work? Let us discuss this first.
Active Object is a concurrency pattern in which we try to separate the invocation of a method from its execution.
The method invocation is made on an Active Object on the client thread and method execution is performed by an independent thread asynchronously without blocking the client thread. Thus, the client thread is not tied-up until the method execution is over. After a method is invoked and the command to execute it is dispatched to the Scheduler, it can perform other tasks.
The key elements in active object pattern are:
- Proxy (or Client Interface) - A public method provided by the active object to clients. An active object creates a message which contains information about the method call and puts into a queue
- Dispatch Queue - A list of pending requests from clients. (Unbounded (LinkedBlocking queue) or Bounded (Blocking queue))
- Scheduler - Run independently on a separate thread and dequeue the message from the queue. Once the message is read, Scheduler will create a one or multiple threads called as Servant to execute the method (message)
- Result Handle (or Callback) - This allows the result to be obtained by proxy after a request is executed.
Example of this pattern I have mentioned in the previous post here.
I hope it helps how this pattern works. Understanding this pattern helps to understand how ExecutorService works internally and also to build a multithreaded responsive application.