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();
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.