0

I'm writing a little Multi-threaded client-server Java application. When the server is started, it creates some objects like an object for db connection, another to manage users and so on. I need them to be accessed from every thread I start. Which is the right way to do that? Passing object istance to every Thread like this:

public class Server{
      private ObjectType1 object1;
      private ObjectType2 object2;
      public void run{
            .......
            new ServerThread(object1,object2);
            .......
      }
}

or passing server istance to every Thread:

public class Server{
      private TypeObject1 object1;
      private TypeObject2 object2;

      public TypeObject1 getObject1(){....}
      public TypeObject2 getObject2(){...}

      public void run(){
          .....
          new ServerThread(this);
          .....
      }
  }

and then from the Thread access objects this way?

server.getObject1();
Alessandro
  • 15
  • 1
  • 5
  • Consider putting references to the required objects into the Server constructor? Or perhaps use static references to object1 and object2 – VILLAIN bryan Jun 27 '15 at 14:58

2 Answers2

0

You can create a special class for storing object references like ObjectHolder where you can put your object1 and object2.

Each thread can access this class with a static method to get objects.

davidluckystar
  • 928
  • 5
  • 15
0

The rightest way to do is passing a single reference to each object, in order to respect the so called Demeter Law: An abstraction should depend on other abstractions directly, not on others abstractions' members.

But in the case that you find there are so many objects needed to be passed, a reasonable (and more comfortable) way to do it is through a new abstraction which encapsulates them all, let's call it Setup: That should be a single javabean with as many members as needed, but no behaviour at all.

By the way: Remember that a JDBC connection must not be used by more than one thread concurrently.

Greetings.

Little Santi
  • 8,563
  • 2
  • 18
  • 46