Posted on Apr 26, 2008

A live template for Java 5 Locks

Every time I used Java 5 new locks I found myself writing the same lock.lock(); try {…} finally {lock.unlock();} over and over again. Sometimes I’ve even coded, unintentionally, a lock.lock() instead of a lock.unlock(). Because of this and other reasons which I won’t share (i.e., I don’t like to copy & paste stuff) :) I decided to automate the addition of the Java 5 locks via IntelliJ live templates. How is this going work? Simply type lock[tab] and voila you will have a new a Java 5 synchronized block written for you


$LOCK$.lock();
try {
    //tocode
} finally {
    $LOCK$.unlock();
}

p.s.,
I almost forgot. In order to make the previous live template to work for both write and read locks, you will have to set the $LOCK$ variable as a variable of the type Lock (i.e., variableOfType(“Lock”)).

Spam Protection by WP-SpamFree