Can I do something like that:
synchronized(isSynchronized ? myLock : null) {
}
I want to disable/enable synchronization through a flag. Is it possible?
You could use a lock ( https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html ) and lock it manually.
if (shouldSync) {
lock.lock();
}
try {
// do your stuff
} finally {
if (shouldSync) {
lock.unlock();
}
}
The parameter passed into the synchronized
block is not a statement but rather a object to synchronize upon (the mutex). To disable synchronization for whatever reason you should encase the statement in a if-condition as such:
if(condition){
synchronized(myLock){
// Critical segment
}
}
note however, if the evaluation of condition
can be dependent on several threads (ie multiple writes to a boolean from different threads) you may need to use an existing thread-safe mechanism like AtomicBoolean
as such:
AtomicBoolean condition = ... // defined elsewhere
if(condition.get()){
synchronized(myLock){
// Critical segment
}
}
if you need conditional synchronization upon a synchronized method, remove the synchronized keyword from the method declaration and move it into the body:
public synchronized void foo(){
// Critical segment
}
to
public void foo(){
if(condition){
synchronized(this){
// Critical segment
}
}
}
Sure. Use an if
before hand. Also, make sure the variable isSynchronized
is marked volatile
.
if (isSynchronized) {
synchronized(myLock) {
// ...
}
}
of course, that won't be synchronized when isSynchronized
is false. And that doesn't sound like a great idea, if it's thread-safe it shouldn't be synchronized. If it isn't thread safe, it should be synchronized.
You can't synchronize of null. So if you have another mutex, then definately you could do something like:
synchronized(isSynchronized ? myLock : myLock2) {
}
else you could check and enter the critical section like:
if (isSynchronized) {
synchronized(myLock) {..}
}
How about this for starters:
if (isSynchronized) {
synchronized(lock) { return doStuff(...); }
} else {
return doStuff(...);
}
private MyType doStuff(...) {
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.