Is it possible to synchronize data members and not methods?
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 ret开发者_JAVA技巧urns 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.
If you make all these methods synchronized, then only one thread at a time will be able to invoke any of the methods, and the list will thus be accessed in a thread-safe way, provided only these methods are able to access the list (i.e. the list is private, and no other method uses the list).
synchronized int getArrayListSize() { ... }
synchronized void addConnection(ServerConnection i_connection) { ... }
etc.
You can synchronize a function by using the synchronized
keyword. For example:
synchronized ServerConnection getClientFromArrayListByIndex(int i_Index) {
ServerConnection client = this.clientConnections.get(i_Index);
// ...
}
If you have one class you can simply prefix your methods with synchronized
; then there is only one thread in any of those methods. But please think if you need this really; it could slow the execution. If you have public fields you should make them private and create getter methods.
You could use Collections.synchronizedList()
to wrap your List
in one for which all of the methods are synchronized.
Whether this is better than synchronizing the methods in your class depends on what else your methods do, and if those things also need to be coordinated.
精彩评论