A shared resource refers to a resource or data that can be accessed or modified by multiple threads or concurrent parts of a program. It could be any piece of data, object, file,
database connection, or system resource that needs to be accessed or manipulated by multiple parts of a program at the same time.
Shared resources should not be used for locking because it increases the chance
of deadlocks. Any other thread could acquire (or attempt to acquire) the same lock while doing
some operation, without knowing that the resource is meant to be used for locking purposes.
For example, a String
should never be used for locking. When a String
is interned by the runtime, it can be shared by multiple threads, breaking the
locking mechanism.
Instead, a dedicated private Object
instance should be used for each shared resource. This minimizes access to the lock instance,
avoiding deadlocks and lock contention.
The following objects are considered as shared resources:
- a reference to Me: if the instance
is publicly accessible, the lock might be shared
- a Type object: if the type class is publicly accessible, the lock might
be shared
- a String literal or
instance: if any other part of the program uses the same string, the lock is shared because of interning