My IDE (JetBrains IntelliJ IDEA) warns me about synchronizing on a method parameter even when it's always an object.
The full warning reads:
Synchronization on method parameter 's' ... Inspection info: Reports synchronization on a local variable or parameter. It is very difficult to guarantee correctness when such synchronization is used. It may be possible to improve code like this by controlling access through e.g. a synchronized wrapper class, or by synchronizing on a field.
My guess is that with auto-boxing, the parameter might be a primitive which gets converted to an object? Although, with auto-boxing, I would assume it's always an object, but maybe not a shared object which means it wouldn't be shared synchronization.
Anyone know why the warning would be present? In my case ShortCircuit
type is always an object and the IDE should be able to know that.
Synchronization risk arises from arbitrageur's uncertainty about when other arbitrageurs will start exploiting a common arbitrage opportunity (Abreu and Brunnermeier, 2002 and 2003). The arbitrage opportunity appears when prices move away from fundamental values.
Synchronization makes sure that shared resources or data can be accessed by only one thread at a time while execution. its advantage is that it prevent data inconsistency and disadvantage is that it makes execution slower as it makes other thread wait till current thread completes execution.
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
The JVM uses the object itself as a monitor (its intrinsic lock) when a class implements method synchronization or block synchronization with the this keyword. Untrusted code can obtain and indefinitely hold the intrinsic lock of an accessible class. Consequently, this can result in a deadlock situation.
The thing is that if you forget to synchronize on ShortCircuit
when using it in other places of your code you might get unpredictable results. It's a lot better to synchronize inside the ShortCircuit
class so it's guaranteed to be thread safe.
Update
If you're moving the synchronization outside of the class it's inherently unsafe for threading. If you want to synchronize on it externally you will have to audit all places it's used, that's why you get the warning. It's all about good encapsulation. It will be even worse if it is in a public API.
Now if you move the fireFinalCallback
method to your ShortCircuit
class you can guarantee that the callback won't fire simultaneously. Otherwise you need to have this in mind when calling the methods on that class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With