Created
February 26, 2016 16:49
-
-
Save rponte/3ef9b0bd700956cefcf9 to your computer and use it in GitHub Desktop.
Concurrency Control for CDI (Interceptor and ReentrantReadWriteLock example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Inherited | |
@InterceptorBinding | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target({ElementType.METHOD,ElementType.TYPE}) | |
public @interface Lock { | |
LockType value() default LockType.WRITE; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Lock | |
@ApplicationScoped | |
public class MyAppScopedBean { | |
@Lock(LockType.READ) | |
public int threadSafeOperation() { | |
... | |
} | |
public void threadUnsafeOperation() { | |
... | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@ApplicationScoped | |
public class OtherAppScopedBean { | |
public int threadSafeOperation() { | |
... | |
} | |
@Lock | |
public void threadUnsafeOperation() { | |
... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More informations, http://www.knitelius.com/2016/01/25/concurrency-control-for-cdi/