Suppose I have four classes in a package named T namely Main, A, B and C
The class Main contains public methods which the classes outside package T access and Main class in turn communicate with other three classes and let some function to happen.

Now I want only a single instance of A, B and C to work in this program, means all are once initialized in class Main and that instances all three classes A,B, and C and used by them.

Previously I created static methods in Main class which returns the required instance of A,B and C to the calling class(A,B,C) but it is creating problems, as I want to that once user stops the function of this package and when he starts it again then the initialization of A,B and C and all fields inside it happens again. Means just like from the beginning.

Any way around for this?

Dani AI

Generated

Static singletons are the root cause here: once A/B/C are held in static fields their lifecycle is tied to the class (and its ClassLoader), so “start a new server session and get fresh instances” becomes awkward. As noted, singleton is a pattern—but as suggested, instance-level ownership is the right fit when each connection needs its own set of objects. The simplest, robust approach is to create a session/context object that owns non-static A, B and C and to create one session per server connection.

A lightweight session example (owns construction and cleanup):

class TSession implements AutoCloseable {
  private final A a;
  private final B b;
  private final C c;

  public TSession(ServerConfig cfg) {
    this.a = new A(cfg);
    this.b = new B(cfg);
    this.c = new C(cfg);
  }

  public A getA() { return a; }
  public B getB() { return b; }
  public C getC() { return c; }

  @Override
  public void close() {
    a.shutdown();
    b.shutdown();
    c.shutdown();
  }
}

Use a new TSession for each server and close it when finished (try-with-resources works well). For multiple concurrent sessions (a “multiton”/registry keyed by server id), keep a thread-safe map of sessions and remove/close the entry on disconnect:

class SessionFactory {
  private static final ConcurrentMap<String,TSession> SESSIONS = new ConcurrentHashMap<>();

  public static TSession get(String serverId, Supplier<ServerConfig> cfg) {
    return SESSIONS.computeIfAbsent(serverId, id -> new TSession(cfg.get()));
  }

  public static void close(String serverId) {
    TSession s = SESSIONS.remove(serverId);
    if (s != null) s.close();
  }
}

Migration checklist: remove static A/B/C, add constructors that accept configuration, replace global static getters with instance getters or a session parameter passed into callers, implement proper shutdown (AutoCloseable), and ensure thread-safety when sharing sessions. Static fields remain useful only for true global singletons; per-connection resources should be explicit and scoped to a session so they can be recreated cleanly for a new server.

Recommended Answers

All 10 Replies

A class with exactly one instance is called a "singleton" class. It is a common pattern in Java applications. Here's a typical implementation:
http://www.javabeginner.com/learn-java/java-singleton-design-pattern

I don't understand what you mean by "user stops the function of this package and when he starts it again then the initialization of A,B and C and all fields inside it happens again". Is there another way you can explain that? Maybe you can post your static methods that return the singletons (one will do, presumambly they are all the same).

Problem with static singleton approach is that once initialized you are bound to use that same instance of that class. But I want to use new instance when I am finished using one round of operation.

I mean to ask, suppose my package T provides a connection to a server and performs some tasks with the help of all classes within it. And when user finishes his work over that server and wants to connect to a new one, then I want the execution of the same process to start again from the class Main and again the new instances of A, B and C should be created with newly assigned arguments.

Presently I'm using Static singleton approach but it is working good only for one round of operation, means only with a one server, when it tries to connect to a new server then problem occurs, because static fields can't be initialized again.

So simply provide instance methods on Main that return reference to A,B, and C. Let the instance of Main decide how to handle them internally. There isn't any need to make them static.

So simply provide instance methods on Main that return reference to A,B, and C. Let the instance of Main decide how to handle them internally. There isn't any need to make them static.

For that i need to make static methods in Main which return the instances of A, B and C which means I also need to make those instances static as well. Problem remains the same.

Why do you think they need to be static?

uhhhh....tell me one thing before, if have something like below:

class A{
  static B;

  A(){
      B=new B();    //Will this initialization occurs once when A1 is created or also
                    //happens when A2 is created
  }
}
class Main{
   public static void main(String[] args){
      A1 = new A();
      A2 = new A();
   }
}

If I execute this, will the initialization of B occurs only once till the program is running or it happens twice?

It will change B every time an instance of A is created. Static is not the same as final.

Static merely means that all instances of a class share that reference instead of each having their own instance variable for it.

but I had read somewhere that static fields get initialized only once? isn't it true?

They are initialized once, but can be re-assigned. "Final" variables cannot be re-assigned after they are initialized.

Ya, I also got it now. I was getting confused previously with the growing complexity of my project. Now also I'm changing some design to make it extensible for concurrent sessions if required, so pulling out all static fields now.

Anyways, thanks your time, you got me some ideas to think about.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.