After reading topics here about Java synchronized methods, I’ve tried to implement it in my multiplayer game because many threads are opened and trying to access the same resource.
I’ve made methods synchronized but that’s doesn’t help me since if I have a data member called ArrayList clientConnection; and the methods that are available are:
int getArrayListSize() {
clientConnection.size();
}
void addConnection(ServerConnection i_connection) {
clientConnection.add(i_connection);
}
void removeConnection(ServerConnection i_connection) {
int index = clientConnections.indexOf(i_Connection);
clientConnections.remove(index);
}
ServerConnection getClientFromArrayListByIndex(int i_Index) {
ServerConnection client = this.clientConnections.get(i_Index);
}
I’ve tried to make a global synchronized method to whenever one want to use one of the methods he needs to pass in an operation type and other data and he locks the function.
The problem is that there are 2 function that return void, 1 returns int and 1 returns ServerConnection so I can’t create that global method.
My question if there is a possible to lock data members and not methods in Java so I can lock the clientConnection data member?
Thanks.
You can synchronize a function by using the
synchronizedkeyword. For example: