I have a class in java that reads UDP packets and puts them in an object (in a basically infinite loop). This object is then accessed in multiple separate threads, but obviously, since it is being filled at the same time, all these getters/setters are in synchronized methods. Problem is, right now these getters have code like this:
public synchronized SomeObject exampleGetter() {
if(this.isReceiving)
return oldCachedObject;
else
return currentObject;
}
Obviously, that’s not quite the best way of doing things, so how should I go about writing methods (lots of different ones) that totally lock the object to one thread at a time and block the others (including the thread that created the object in the first place)? I looked at synchronized blocks, but I am kinda confused as to what effect the “lock object” has, is that the object that has access to the block at that given time? Any advice would be appreciated. Thanks!
The
synchronizedkeyword synchronizes on the whole object instance not just the setter. I would rather go for a fine grained locking strategy or better… use a thread safe data structure where you store and get the received data. I personally love theBlockingQueue<T>whereTis the type of data you receive on the network.So suppose you are receiving
Objects over a socket:And in your socket you could do this whenever you receive data:
Any thread that wants to get data should do:
This latter method call will block the calling thread until there is an element available on the queue (check this out for more details)
I hope this helps