javamultithreadingperformancelockingreentrancy

ReentrantLock: Lock/Unlock speed in single-threaded application


i'm using some ReentrantLock to synchronize access to a List across multiple threads. I just write a generic

try {
   lock.lock();
   ... modify list here
} finally {
   lock.unlock();
}

everywhere. I just noticed though, that most of lists across the code are going to be used by a single (gui dispatch-) thread only.

Now i'm not sure if i should remove the lock in these cases, as it might speed up my code. How fast is ReentrantLock? Is the lock() operation somehow faster if the thread himself was the "prior owner" of the lock, even if he unlock() it?


Solution

  • No matter how fast it is, it would certainly be slower than no locking, if just by a very small amount. I would personally prefer correctness over speed gain (which won't be a lot) and keep the code the way it is (especially if it is already tested) unless you have identified "locking" to be a bottleneck.