Skip to content

Instantly share code, notes, and snippets.

@rponte
Created February 26, 2016 16:49
Show Gist options
  • Save rponte/3ef9b0bd700956cefcf9 to your computer and use it in GitHub Desktop.
Save rponte/3ef9b0bd700956cefcf9 to your computer and use it in GitHub Desktop.
Concurrency Control for CDI (Interceptor and ReentrantReadWriteLock example)
@Inherited
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface Lock {
LockType value() default LockType.WRITE;
}
@Lock
@Interceptor
public class LockInterceptor {
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
@AroundInvoke
public Object concurrencyControl(InvocationContext ctx) throws Exception {
Lock lockAnnotation = ctx.getMethod().getAnnotation(Lock.class);
if (lockAnnotation == null) {
lockAnnotation = ctx.getTarget().getClass().getAnnotation(Lock.class);
}
Object returnValue = null;
switch (lockAnnotation.value()) {
case WRITE:
ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
try {
writeLock.lock();
returnValue = ctx.proceed();
} finally {
writeLock.unlock();
}
break;
case READ:
ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
try {
readLock.lock();
returnValue = ctx.proceed();
} finally {
readLock.unlock();
}
break;
}
return returnValue;
}
}
@Lock
@ApplicationScoped
public class MyAppScopedBean {
@Lock(LockType.READ)
public int threadSafeOperation() {
...
}
public void threadUnsafeOperation() {
...
}
}
@ApplicationScoped
public class OtherAppScopedBean {
public int threadSafeOperation() {
...
}
@Lock
public void threadUnsafeOperation() {
...
}
}
@rponte
Copy link
Author

rponte commented Feb 26, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment