My java code looks like this:
class xHandler
{
private Channel _channel;
// Methods...
void init()
{
_channel = new Channel(...);
synchronized (_channel)
{
// Do some stuff here...e.g.
_channel.send("...");
}
}
}
In other files(threads) I create instances of Channel and send stuff with the use of the object, but only in the init method mentioned above I need it to be sync’ed and no other thread should open a channel and send something during this period.
FindBugs gives me a warning called: Method synchronizes on an updated field
This method synchronizes on an object referenced from a mutable field.
This is unlikely to have useful semantics, since different threads may be synchronizing on different objects.
How can I get this issue right? Is it possible to trigger this issue easily with a simple test?
Seems like your code is not doing what you are thinking that it is doing. Since you are creating a new
Channelobject perxHandlerinstance, and acquiring this specificChannellock, two threads may run concurrently.What you really need to do is either:
Channelobject that you want to sync for multiplexHandlerinstances (Example: receive a instance ofChannelonxHandlerconstructor and assign it to_channel, remove the_channel = new Channel(...);line and keep your sync code as it is).Channel.classwhich will mean that two different instances ofxHandlerwill never be able to use anyChannelsimultaneously.Example of sharing a specific
Channelfor two different xHandlers: