How do I restrict the creation of Java objects?
You can use the active object pattern as an alternative to the standard pools.
Since you need multiple such objects, the objects are probably stateful.
Therefore, you may have a list of active objects to which you send requests through some proxy.
The idea is this:
1) There is a "scheduler", which in its simplest form is a thread waiting on a blocking queue and processes requests one by one. Notice how the method is started, not thread.start ().
2) You have a blocking queue of services to which you send requests, which are picked up by the "scheduler" thread.
3) Your active entity provides services that are processed by the Scheduler.
Then you can put a static list of these active objects behind some proxy that will be responsible for delegating requests to your active objects using round robin deployment or any other balancing strategy.
Here's an example from Wikipedia:
class BecomeActiveObject
{
private double val = 0.0;
private BlockingQueue<Runnable> dispatchQueue
= new LinkedBlockingQueue<Runnable>();
//
public BecomeActiveObject()
{
new Thread(
new Runnable()
{
@Override
public void run()
{
while (true)
{
try
{
dispatchQueue.take().run();
} catch (InterruptedException e)
{ // okay, just terminate the dispatcher
}
}
}
}
).start();
}
//
void doSomething() throws InterruptedException
{
dispatchQueue.put(
new Runnable()
{
public void run() { val = 1.0; }
}
);
}
//
void doSomethingElse() throws InterruptedException
{
dispatchQueue.put(
new Runnable()
{
public void run() { val = 2.0; }
}
);
}
}
source to share