简体   繁体   中英

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 :-) .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM