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[] = {
  private static final int NUMBER_OF_SERVERS = 1000;

  public ServerTest() {
  for(int i=0; i < NUMBER_OF_SERVERS; ++i) {
  Server server = ServerFactory.getServer(getRandomServerType());

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

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



  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

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

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

  4. Great Article android based projects

    Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai


Post a Comment

Popular posts from this blog

ActiveMQ, easy to use open source message oriented middleware (MOM)

Basic Send Message to MQ with Java and IBM MQ JMS

Automated Service Monitoring with F5, Consul and Python F5 SDK