Question

In: Computer Science

When it is necessary to work with a large number of objects that are particularly expensive...

When it is necessary to work with a large number of objects that are particularly expensive to instantiate and each object is only needed for a short period of time, the performance of an entire application may be adversely affected. An object pool design pattern may be deemed desirable in cases such as these.  The object pool pattern is a design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand.  A client of the pool will request an object from the pool and perform operations on the returned object.  When the client has finished, it returns the object to the pool rather than destroying it, allowing it to be used again in the future without repeating the computationally expensive instantiation process. It is important to note that once an object has been used and returned, existing references will become invalid.

When a new object is needed, it is requested from the pool. If a previously prepared object is available it is returned immediately, avoiding the instantiation cost. If no objects are present in the pool, a new item is created and returned.  In some object pools the resources are limited so a maximum number of objects is specified.  If this number is reached and a new item is requested, the thread will be blocked until an object is released back into the pool.

Object pools are primarily used for performance.  For example, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required.  Connection pools are used to enhance the performance of executing commands on a database. Opening and maintaining a database connection for each client, especially requests made to a dynamic database-driven website application, is costly and wastes resources.  In connection pooling, after a connection is created, it is placed in the pool and it is used again so that a new connection does not have to be established.  If all the connections are being used, a new connection is made and is added to the pool. Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database.

Consider a dummy ServiceObject class that has a single state variable (String myState) and a single method doSomething() that just prints “myState”.   Each client of ServiceObject will have its own “myState”

  1. Design and implement a class(es) that allows a pool of a specified number (n) of instances of ServiceObject.  The class(es) should offer the following methods:
  • getInstance():  returns to a client an instance if one is available.  If no instance is available and the maximum number of instances (n) is not reached, an instance is created and returned.  The instance returned by the getInstance() method should not be used again until" released.  
  • releaseInstance(ServiceObject):  releases the object for future use

Solutions

Expert Solution

---------------------------------------------------------------------------ANSWER----------------------------------------------------------------

  • OBJECTPOOL CLASS

import java.util.HashSet;
import java.util.Set;


public class ObjectPool<T>
{

private Set<T>available = new HashSet<>();
private Set<T>inUse= new HashSet<>();

private int MAXTotalObjects;
private int counter = 0;


private ObjectPool<T>instance = null;

public ObjectPool<T>GetInstance()
{

if (instance == null)
{
instance = new ObjectPool<T>();
}
else
{
System.out.print("This is singleton!");
}
return instance;
}


public T getInstance() {

if (available.size() != 0 &&available.size() <= 10)
{
T instance = available.iterator().next();
available.remove(instance);
inUse.add(instance);
counter--;
return instance;
}
else
{
T obj = (T) new ServiceObject();
inUse.add(obj);
return obj;
}
}

public booleanreleaseInstance(T instance) {
if (counter <= MAXTotalObjects)
{
available.add(instance);
counter++;
inUse.remove(instance);

}
else
{
System.out.println("To much object in pool!");
}
return false;
}

public void SetMaxPoolSize(int settingPoolSize)
{
MAXTotalObjects= settingPoolSize;
}

@Override
public String toString() {
return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
}
}

  • OBJECT SERVICE CLASS

public class ServiceObject {
private String myState;

public ServiceObject()

{

}

public ServiceObject(String myState) {
this.myState= myState;
}

public String getMyState() {
return myState;
}

public void setMyState(String myState) {
this.myState= myState;
}

public String doSomething() {
return myState;
}
}

  • POOL TEST CLASS

public class PoolTest {

public static void main(String[] args)
{
ObjectPool<ServiceObject>objPool = new ObjectPool<ServiceObject>().GetInstance();
objPool.SetMaxPoolSize(5);
ServiceObject obj = objPool.getInstance();
ServiceObject obj1 = objPool.getInstance();
ServiceObject obj2 = objPool.getInstance();
ServiceObject obj3 = objPool.getInstance();
ServiceObject obj4 = objPool.getInstance();
ServiceObject obj5 = objPool.getInstance();
ServiceObject obj6 = objPool.getInstance();
ServiceObject obj7 = objPool.getInstance();
ServiceObject obj8 = objPool.getInstance();
ServiceObject obj9 = objPool.getInstance();
ServiceObject obj10 = objPool.getInstance();
ServiceObject obj11 = objPool.getInstance();

System.out.println(objPool.toString());
objPool.releaseInstance(obj);
objPool.releaseInstance(obj1);
objPool.releaseInstance(obj2);
objPool.releaseInstance(obj3);
objPool.releaseInstance(obj4);
objPool.releaseInstance(obj5);
objPool.releaseInstance(obj6);
objPool.releaseInstance(obj7);
objPool.releaseInstance(obj8);

System.out.println(objPool.toString());
}
}   

------------------------------------------------------------------------------------------------------------------------------------------------------



Related Solutions

Healthcare is expensive. It takes an enormous amount of capital to secure the necessary resources to...
Healthcare is expensive. It takes an enormous amount of capital to secure the necessary resources to finance the care delivery continuum. The cost and sources of that capital is critical to being able to understand the cost of conducting business in general and also forms the basis on which future projects can be evaluated on a quantitative basis (e.g., capital budgeting, lease financing, etc.). For this discussion, do the following: Consider you are determining which type of financing to be...
Glucose is a necessary substrate for ATP production in many cells, particularly the neurons in the...
Glucose is a necessary substrate for ATP production in many cells, particularly the neurons in the nervous system. Inability to maintain blood glucose between meals leads to feelings of fatigue. There are many steps in the extraction of energy from glucose for production of usable energy in a cell. Please discuss the extraction of energy from glucose by cells for both aerobic and anaerobic energy processes. Calculate the energy yield per molecule of glucose for each process (show your work)....
How many ways to group 75 objects into 3 groups if any number of objects can...
How many ways to group 75 objects into 3 groups if any number of objects can be in the 3 groups if each group must have 25 objects?
Binomial distributions are approximately normal when the number of trials is large, and the probaility of...
Binomial distributions are approximately normal when the number of trials is large, and the probaility of success is not near zero or one. A player flips an unbiased coin 1,296 times. a. What is the probability of the coin landing on heads between 612 and 684 times?
Let ?̅ = sample mean in a SRS of ? objects from a large population. For...
Let ?̅ = sample mean in a SRS of ? objects from a large population. For each of the following, find ?(?̅), ???(?̅), ??(?̅) and indicate whether a normal distribution would be a good approximation to the shape. a. severely right-skewed population, ? = 183, ? = 106, ? = 35 b. normal population, ? = 515, ? = 116, ? = 50 c. symmetric, unimodal population, ? = 10, ? = 3, ? = 14 d. mildly left-skewed population,...
State University employs a large number of graduate students to work as teaching assistants. The teaching...
State University employs a large number of graduate students to work as teaching assistants. The teaching assistants often complain about their work. They feel that faculty and administrators demand too much. A common complaint is their low wages. The graduate students frequently point out that they do much the same work as faculty members, yet they receive only a very small percentage of the pay that faculty members receive. They also claim that faculty members frequently treat them unfairly. Teaching...
State University employs a large number of graduate students to work as teaching assistants. The teaching...
State University employs a large number of graduate students to work as teaching assistants. The teaching assistants often complain about their work. They feel that faculty and administrators demand too much. A common complaint is their low wages. The graduate students frequently point out that they do much the same work as faculty members, yet they receive only a very small percentage of the pay that faculty members receive. They also claim that faculty members frequently treat them unfairly. Teaching...
The number of coins that Jake spots when walking to work can be modeled as a...
The number of coins that Jake spots when walking to work can be modeled as a Poisson process with unit rate of 3/half an hour. Suppose it takes Jake half an hour each day to walk to work, and half an hour to walk back. Each coin is equally likely to be a penny, a nickel, a dime, or a quarter. Jake ignores the pennies but picks up the other coins. (a) Find the expected amount of money that Jake...
Provide some definitions and descriptions of the following objects with diagrams if necessary 1. White dwarf...
Provide some definitions and descriptions of the following objects with diagrams if necessary 1. White dwarf 2. Rotational Curve 3. HII region 4. Virial Theorem 5. Chandrasekar mass 6. Critical cosmological density 7. Gravitational wave 8. Clusters of galaxies
What are some disadvantages to having a large number of choices when it comes to purchasing...
What are some disadvantages to having a large number of choices when it comes to purchasing a product like a television?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT