That is the problem I have with that method: why is it there at all? The only way I can think of testing it is to predict what sort of String it will return, which is very awkward without reading directly from the database. It is also awkward because the method isn't some sort of function; you cannot pass any sort of input to it and predict its output from that input.
This morning, I wrote:Why are you trying to turn your List into a single String?
Good point; it might be possible to have different locks for different methods. That is what the read‑write locks are all about.
Tim Moores wrote:. . . As you said, synchronizing only allows a single thread to run the code . . .
Another way to put what Paul said is that the final modifier would be applied to the class, not to the fields.
Paul Clapham wrote:. . . No, it doesn't. A final class can't be extended . . . .
Execution speed should probably be the last consideration when designing an app. It is much more important to get the number of classes rright, and any inheritance hierarchy. It might be slightly slower to compile more classes, but that is the least of our worries.
Paul Clapham wrote:. . . But why would that matter?
In that code, although the assignment in line 9 is atomic, you do not know whether a second thread will read the new value or the old value of i. So you use a Lock object to synchronise the two methods. Note that the lock() call doesn't go in a try, but the unlock() call has to be in a finally.That's a very simple and naïve example, but if you are trying to call setI(), and a different thread attempts to use getI(), that second thread cannot acquire the lock on line 24 until after the lock has been released on line 18. The same would happen if a thread executes the getI() method. If you are using beginners' code and un‑comment line 14, the thread executing that code already holds the lock. When it reaches line 24, it can lock the lock again with a count of 2. You should find it easy to work out that, by the time the setI() method completes on line 18, the lock count is back to 0.
Vaibhav Gargs wrote:. . . "As the name says, ReentrantLock allow threads to enter into lock on a resource more than once. . . . ."
I am just wondering why someone would take the lock more than once?
Yes, you are. The Lock reference points to an instance of the ReentrantLock class, so that is an object. You are not using its intrinsic lock but explicitly counting how often it has been locked.
. . . we are not calling methods on any object . . .
It is used instead of the keyword synchronized.
Is this same thing as synchronized locks?