Getting rid of boilerplate code for ReentrantReadWriteLock

Got tired of the idioms alike?

rwl.readLock();
try {
    // thread
    // unsafe
    // code
} finally {
    rwl.readLock().unlock();
}

It is 2017 and Java 8 have been released in 2014! Using lamdas makes the code keen and clean. Here what you get:

// You can assign the result to a variable of the type you need:
String s = callReadLocked(() -> {
        // thread
        // unsafe
        // code
        return someString;
    });
}

// If nothing needs to be returned, just return anything:
callReadLocked(() -> {
        // thread 
        // unsafe
        // code   
        return null;
    });
}

For the magic to work you need to define a couple of methods and a functional interface:

private <T, E extends Throwable> T callReadLocked(Function<T, E> function) throws E {
    rwl.readLock().lock();
    try {
        return function.apply();
    } finally {
        rwl.readLock().unlock();
    }
}

private <T, E extends Throwable> T callWriteLocked(Function<T, E> function) throws E {
    rwl.writeLock().lock();
    try {
        return function.apply();
    } finally {
        rwl.writeLock().unlock();
    }
}

@FunctionalInterface
private interface Function<T, E extends Throwable> {
    T apply() throws E;
}

If you hate returning null which might prevent you from writing one-liners - feel free to add a couple of call methods with void return type, as well as second functional interface with void return type for method apply()

Комментарии

Популярные сообщения из этого блога

Spring Boot, JUnit and org.json collision

Changing channel colors at Saleae Logic

Mime type issue with Geoserver and Spring