Java Ping Servers - Flyweight Reduce Memory Footprint

package ServerProbe;

/*
 * Simple demonstration how to use the flyweight design pattern to improve performance and reduce
 * memory footprint.
 * Create a ServerFactory based on a pre-defined number of server types e.g. Windows, Unix etc
 *  Within Server object, for example have a shareable method such as pingIT, also the server_type is
 * shareable
 * Pass IP address and ping duration in as parameters
 *
 */

public class Server {
  String server_type;

  Server(String type){
  server_type = type;
  }

  String getType() {
     return server_type;
  }

  public void pingIT(String ip, int duration) {
  System.out.println("Pinging ->" + server_type + " IP -> " + ip);
  }

  public String toString() {
      return server_type;
  }
}

import java.util.HashMap;

public class ServerFactory  {
  private static final HashMap serverByType = new HashMap();

  public static Server getServer(String serverType) {
     Server server  = (Server) serverByType.get(serverType);

     if(server == null) {
        server = new Server(serverType);
        serverByType.put(serverType, server);
        System.out.println("Creating " + serverType + " Server Container");
     }
     return server;
  }
}

public class ServerTest {
  private static final String ServerTypes[] = {
  "Windows",
  "AIX",
  "UNIX",
  "Solaris",
  "Linux"
  };
  private static final int NUMBER_OF_SERVERS = 1000;

  public ServerTest() {
  for(int i=0; i < NUMBER_OF_SERVERS; ++i) {
  Server server = ServerFactory.getServer(getRandomServerType());
  server.pingIT("192.168.1."+i,100);
  }
  }

  private String getRandomServerType() {
return ServerTypes[(int)(Math.random()*ServerTypes.length)];
}

  public static void main(String[] args) {
  ServerTest test = new ServerTest();
  }

}

Comments

Post a Comment

Popular posts from this blog

Basic Send Message to MQ with Java and IBM MQ JMS

Basic Receive Message to MQ with Java and IBM MQ JMS

Configure Database Connection using MyBatis