Reputation: 1489
I'm reading the netty source code, and come across a synchronized
on formal parameter.
AbstractBootstrap(AbstractBootstrap<B, C> bootstrap) {
localAddress = bootstrap.localAddress;
synchronized (bootstrap.options) {
options.putAll(bootstrap.options);
}
}
localAddress
is not synchronized
because it's declared as volatile, any change to it is visable to other thread.
But I don't understand to synchronized
on a formal parameter bootstrap
.
bootstrap
is a formal parameter, every thread has it's own copy.
synchronized
on it only effect it's own thread? Is this opinion correct?
synchronized (bootstrap.options)
is to prevent bootstrap.options
to be modified outsides this class or to prevent this.options
to be modified by other thread?
Upvotes: 2
Views: 79
Reputation: 11907
bootstrap is a formal parameter, every thread has it's own copy. synchronized on it only effect it's own thread? Is this opinion correct?
No, this is not strictly correct. The parameter bootstrap contains a reference to an object, it is not a local copy of the object. Therefore other threads could have their own references to the same instance of the object.
synchronized (bootstrap.options) is to prevent bootstrap.options to be modified outsides this class or to prevent this.options to be modified by other thread?
Kinda. It will block until the current thread can acquire exclusive access to the the object that is in bootstrap.options
. It appears to be doing this because bootstrap.options is some kind of collection that is not itself thread safe, and so it is protecting the behaviour of the map under concurrent usage.
Upvotes: 2
Reputation: 1755
Most likely, this looks to be the case to lock the bootstrap options (some mutable map) while merging options. As there is no additional source code, what I can infer is that bootstrap instance (which is passed as parameter) and its options field is shared between different threads. That's why the synchronization is required.
Upvotes: 0
Reputation: 6322
Every constructor invocation receives a copy of the reference variable pointing to an AbstractBootstrap
instance.
If you reference another instance within the constructor, the change will only affect the copy that constructor received. But any change in the AbstractBootstrap
instance will be reflected to all the threads sharing it.
Hope it helps,
Upvotes: 0