There are a few common patterns for priority handling.
Use thread priority
If you only have two threads, and you spawn the threads yourself, then you can set their priority.
Thread t = new Thread(yourRunnable);
t.setPriority(Thread.MAX_PRIORITY);
// or MIN_PRIORITY
// or something in between
Use a priority based ExecutorService
You could refactor all your calls to the manager
into Runnable
or Callable
instances.
Then, using a PriorityQueue and a Comparator of your own, it's easy to dispatch your work units to a pool of threads.
See : How do I implement task prioritization using an ExecutorService in Java 5?
If you really need a strong priority, this is a solution I'd recommend because the conccurent package is the current standard, "go-to", solution for concurrency, and its scalable to as many thread and priorities as you need.
Alternative options include:
Use multiple ExecutorServices
You could be to use two ExecutorService instances, one with 2 threads and another with 1, the idea would be to allow more threads to deal with your most important work, and less thread to the less important.
This is more a workaround than a solution, but it's one that's easy and also (almost) guarantees your high priority task will not starve lower priority ones.
Use Locking
This is a more error prone way of solving the issue. But you could imagine locking access to your manager instance so that when an addQueue
event arises, then calls to sendData
get locked out untill the first event stops.
But this is actually not a priority implementation, it's more of a "mutual exclusion" pattern.
Use producer / consummer pattern
You can have producer threads that create work units into one (or more) queues. Consumer threads then pop work out of this (these) queues and deal with it (call the manager).
If your queue is a PriorityQueue or if you have a "high priority" and a "low priority" event queues, then your consummer has the choice of how it handles the priority based on your needs.
In any case, you should make sure you understand the ramifications correctly.
- Priority implies that the risk of starvation is real. You should
balance your needs accordingly to prevent high priority to starve
low priority
- Are you really looking for Thread priority handling, or
can alternative patterns such as mutual exclusion or
producer/consummer solve the issue ?