I have a number of default methods in interfaces that need synchronization and it seems that only this
is available:
default void addUniqueColumns(List<String> names) {
synchronized (this) {
... do something
}
}
The problem is, I want to synchronize on a private lock instead of this
for better control:
default void addUniqueColumns(List<String> names) {
synchronized (lock) { // how to get a private lock in a default method??
... do something
}
}
Solutions? Clever workarounds? Or just live with it :) !
You can put the lock object into a pubic static field of a package-visible class, letting all your default methods share the lock. The lock remains visible inside your library, but since classes with default access are not visible outside your library, the lock would be private to the users of your interface outside your library:
As far as your library is concerned as a whole, this trick gives you the same advantages as using a
private
lock object does compared to synchronizing onthis
, because it prevents malicious code written by outsiders from accessing your lock. Of course the lock can be grabbed by any part of your library.