Thread locks in if statements

I have a code block like this:

if(supportsSomeStuff()){
     .....
     .....
}
else {
     .....
     .....
}

Now I want to have this code block in multiple reads, single write locks. In this case, it is better to lock the if statement and release the lock after if, then lock in the else statement and release it when you're done?

Or, can I just block this if-else case and free it when done?

If I need to decide on this, what factors need to be taken into account?

Please let me know if you need more information.

+3
source share
5 answers

Are you considering the following two options?

synchronized(lock) {
    if(supportsSomeStuff()){
         .....
    }
    else{
         .....
    }
}

against.

if(supportsSomeStuff()){
    synchronized(lock) {
     .....
    }
}
else{
    synchronized(lock) {
     .....
    }
}

() , if . ( supportsSomeStuff() ), , .

+1

,

, StringBuilder, StringBuilder changevalue SomeStuff

if(supportsSomeStuff()){
     //Considering that if will be executed when write needs to be done and else when read to be done 
     copyOnWriteStringBuilder = new StringBuilder(changingvalue.toString());//This will ensure that before every write you have taken a backup so concurrent read will see the last updated values
     synchronized(changingvalue) {
        //doSomething and then place the updated value in copyOnWriteStringBuilder too
     }
  }
else{
    return copyOnWriteStringBuilder; // This piece for read no locking
}
0

:

  • if else.
  • lock(); try { ... } finally { unlock(); }, . , , , .

, - , -.

lock.lock();
try {
   if(supportsSomeStuff()){
      ...
   } else {
      ...
   }
} finally {
   lock.unlock();
}

, if , . , , - , , , , .

0

, , .

:

  • ;
  • , .

.

By the way, many people offer a built-in synchronized lock, but since you mention that you only need one write stream, then depending on your situation, you can get a higher bandwidth using ReentrantReadWriteLock.

0
source

Reading is not exclusive, but is written; which means that there can be several simultaneous readings, but there can only be one record, and when recording is not performed, reading is not allowed.

It depends on what you do, where. Limit the block where you write the minimum.

-1
source

All Articles