How do I restrict the creation of Java objects?

I have an application where I have heavy objects, I want to restrict the creation of the object to some number x (this will not affect my application). how to do it?

+3


source to share


2 answers


Modifying the Singleton template. You can use the variable count. You need the Constructor to be closed in order to have control over no. copies.



+4


source


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; }
                }
        );
    }
}

      

0


source







All Articles