Smarty77
Smarty77

Reputation: 1348

Java Static Variable of instance overwritten in another instance ?

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

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

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

Dima
Dima

Reputation: 8652

static variable is not an instance variable, its the same one for every instance. its a class variable so if some instance touch it, it will change for all. you can read more about static variables here

Upvotes: 2

Related Questions