The solution what came to my mind was implementing a scheduler using a CommandQueue managed by a Thread. So as everytime an incoming request from a device arrives to my server, it defines which kind of request is, and push it into the CommandQueue if needed, then the command is sent by the manager Thread and retrieves the result to the requester Thread.
From now I will write my posts in english and I'm using GitHub to share my code and projects so here is the current example repository.
https://github.com/ivillalba/synchronous-resource-sharing.git
BlockingQueueManager Class
This class acts as a PriorityBlockingQueue wrapper. Its responsability is to handle every incoming task queued. It basically does two things:
- Waits for a queued task. If there is no tasks in the queue it remains blocked waiting for one.
- Processes a task in a synchronized block, when the task process is completed, the BlockingQueueManager wakes up the Producer thread by calling task.notify() which is waiting at the task.wait() sentence.
Producer Class
This class simulates a task producer. It just builds a random task using the task factory class and pushes it into the PriorityQueue by calling the this.taskQueue.add() method. Then waits for the task to be processed by calling newTask.wait() into a synchronized block.
Task Class
Tasks will have 3 properties.
- Priority: Sets the priority of the task.
- Name: Is the task name.
- Result: This property will be set by the manager with the task processing result.
Task implements Comparable interface since its needed by PriorityBlockingQueue to have a way to compare different instances of its queue collection items.
TaskFactory Class
SynchronizedResourceSharing (Main Class)
Output
The result of the application execution is a non deterministic output since the tasks are randomly generated hence their priorities and names.
Task taken.
I'm cooking...
Task done.
Task taken.
Producer[3]: My task has been completed with result 1
I'm programming in JAVA...
Task done.
Producer[1]: My task has been completed with result 2
Task taken.
I'm programming in JAVA...
Task done.
Producer[0]: My task has been completed with result 3
Task taken.
I'm cooking...
Task done.
Producer[2]: My task has been completed with result 4
Task taken.
I'm programming in JAVA...
Task done.
Producer[4]: My task has been completed with result 5
Interrupt signal received. Finishing...