Reputation: 1348
Im suffering from more complex problem. I 've got server program, when server accepts connection it creates new socket and communicate throught it in new thread. This new thread creates an instance of class 'Protocol' and class protocol contains static variable.
static Player player;
This class contains method where in which this player variable is initialized. There is the code sample
synchronized(pMap){
if (pMap==null || pMap.PlayerNumber>3)
return false;
player = pMap.createPlayer(Thread.currentThread().getId());
}
When first player joins everything works fine, but when the 2nd player joins server, calls this method within his thread (2nd thread) and creates new protocol instance, variable Player in 1st thread cointains new instance of player(instance created in 2nd thread) instead of instance created when there was no second thread.
Long story short, all new threads always have same Player instance, even that in every thread there is always created new instance of Player. Im new to OOP, maybe im not understand correctly the meaning of 'static'. I would be glad if someone could explain this :-) .
Upvotes: 1
Views: 806
Reputation: 726479
static
means "shared among all instances". It appears that your code has some logic that prevents creation of more than three players at the same time. In this case, it is incorrect to assign players to a shared static
variable.
You should make Player
non-static in your class, or at the very least use a thread-local storage for it. Otherwise, all instances of your Protocol
are going to share the same player, regardless of the thread on which they run.
Upvotes: 3