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

  1. Thank you for Sharing. I'm working in brave technologies private limited, We are the best erp software developers based in chennai. erp providers in chennai

    ReplyDelete
  2. I heve read your blog it's very interesting and informative. Keep sharing.
    erp in chennai | erp software solutions in chennai

    ReplyDelete
  3. I found a lot of interesting information here. A really good post
    office 2011 mac download deutsch

    ReplyDelete

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

Creating a simple Alert / Success Message with ASP.NET/VB using Bootstrap