3

I have a class which will get data from socket. I should create 5 instance of this class according several condition. How can i check if a specific instant of this class is running, other ways creating that specific instance which is missing? This is Some code snip:

public void checkReachabilityOfHosts(){

    String[] host = {"192.168.30.190", "", "", "", "" };

    for (String h : host) {
        if (h.length() > 0) {
            if (isHostReachable(h)) {
                DeviceByteReader deviceByteReader = new DeviceByteReader(h, 3001);
                deviceByteReader.setUpConnection();
                deviceByteReader.getSMessage();
                deviceByteReader.tearDownConnection();
            } else {
                return;
            }
        }else {
            return;
        }
    }
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
michdraft
  • 197
  • 2
  • 3
  • 10

2 Answers2

1

You can modify your class and add special id field to it. This ID will be generated into the class constructor and you can always identify your instance. To generate ID use either time stamp in milliseconds or random number or static instance counter or, if you want to create really unique ID across the world use UUID.randomUUID().

Other solution is just use System.identityHashCode(obj). This is unique across all objects within current instance of your JVM.

AlexR
  • 114,158
  • 16
  • 130
  • 208
1

Use the factory pattern: Give each instance a constant key (for example the IP address).

The factory has a cache which uses the key to lookup existing instances. If there is no instance in the cache, create a new one.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820