tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Design Patterns > Java Design Patterns > Nton

Nton 

This example shows creating an Nton. Means the application is provided with N-instances of a particular class. Each call to getInstance method is served with one of the available instances in round robin fashion. The number of instances required by the application is configurable.

Behaviour & Advantages

  • The number of instances required by the application should be configurable.
  • The class should have a private constructor to avoid creation of external instances.
  • It should have static synchronized method which returns one of the available instances in round robin fashion (Thread synchronized has to be taken care to avoid creation of duplicate instances)
  • In case of service based Nton's, this provides a way of load balancing by delegating the responsibility of handling the request to one of the available and identical services.

Nton implementation is shown below,

File Name  :  
com/bethecoder/tutorials/dp/singleton/nton/Nton.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.dp.singleton.nton;

import java.util.ArrayList;
import java.util.List;

public class Nton {

  /**
   * Configure the number of instances required in the application.
   */
  private static final int NUM_OF_INSTANCES = 5;
  private static final List<Nton> instanceList = new ArrayList<Nton>();
  private static int instanceRequestCount = 0;
  private int instanceNum;
  
  /**
   * Make sure to have private default constructor.
   * This avoids direct instantiation of class using 
   * new keyword/Class.newInstance() method
   */
  private Nton() {
  }
  
  public static synchronized Nton getInstance() {
    
    Nton instance = null;
    
    if (instanceList.size() == NUM_OF_INSTANCES) {
      instance = instanceList.get(instanceRequestCount % NUM_OF_INSTANCES);
    else {
      instance = new Nton();
      instance.instanceNum = instanceList.size() 1;
      instanceList.add(instance);
    }
    
    instanceRequestCount ++;
    return instance;
  }
  
  public int getInstanceNum() {
    return instanceNum;
  }
  
  public String toString() {
    return "Nton : " + getInstanceNum();
  }
  
}
   

File Name  :  
com/bethecoder/tutorials/dp/singleton/nton/Test.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.dp.singleton.nton;

public class Test {
  
  public static void main (String [] args) {
    
    for (int i = ; i < 20 ; i ++) {
      System.out.println(Nton.getInstance());
    }
    
  }
}
   

It gives the following output,
Nton : 1
Nton : 2
Nton : 3
Nton : 4
Nton : 5
Nton : 1
Nton : 2
Nton : 3
Nton : 4
Nton : 5
Nton : 1
Nton : 2
Nton : 3
Nton : 4
Nton : 5
Nton : 1
Nton : 2
Nton : 3
Nton : 4
Nton : 5



 
  


  
bl  br