Coding: Avoiding unnecessary locking
The code bellow, extracted from
java.util.regex.Pattern
, avoids unnecessary locking. Look the statement if (!compiled) {
, it appears twice times because in the first time, we don't need to create a lock point, but if the code isn't "compiled" (!compiled
evaluates true), so it creates a lock point and because the condition of variable compiled
can be changed from the first time that it was evaluated (eg.: now !compiled
can be evaluated to false, because it was "compiled" by another thread, between the first evaluation and the lock point). It avoids unnecessary retention in the case of the first evaluation was false
, because in the entire lifecicly of the object there is only a transition of the variable compiled
, from false
to true
, so only one time in the entire lifecicly, the lock point will be reached. It's a good technique! Think about it!
1: /** 2: * Creates a matcher that will match the given input against this pattern. 3: * </p> 4: * 5: * @param input 6: * The character sequence to be matched 7: * 8: * @return A new matcher for this pattern 9: */ 10: public Matcher matcher(CharSequence input) {11: if (!compiled) { 12: synchronized(this) { 13: if (!compiled) 14: compile(); 15: } 16: }17: Matcher m = new Matcher(this, input); 18: return m; 19: } 20:
0 Comments:
Post a Comment
<< Home