Tuesday, September 21, 2010

EJB.next Interceptor Improvements - Method signatures

Interceptors are great, but some parts of them are odd when applied practically. For as fundamentally reflective as interceptors are, it isn't possible to pass all interceptable calls through a single method, like so:

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.interceptor.AroundInvoke;
import javax.interceptor.AroundTimeout;
import javax.interceptor.InvocationContext;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;

public class StatsInterceptor {

    @PostConstruct
    @PreDestroy
    @PrePassivate
    @PostActivate
    @AroundInvoke
    @AroundTimeout
    public Object intercept(InvocationContext context) throws Exception {
        final long start = System.nanoTime();
        try {
            return context.proceed();
        } finally {
            final long nanos = System.nanoTime() - start;
            final long millis = MILLISECONDS.convert(nanos, NANOSECONDS);
            System.out.println("invoke time "+ millis +" milleseconds");
        }
    }
}

This looks very nice, but currently is not legal. The spec currently requires different formats for callback-based interception vs business-method-based interception. This sounds like a nice safe and conservative rule, but is it benefiting users? Not really. Let's see what we have to do to our interceptor to make it compliant.

First, callback intercept methods are not allowed to return anything and must have a void return type. The logic here is that since callbacks have no return value, interceptors should know this. So fine, let's work around that and just make a new method:

    @PostConstruct
    @PreDestroy
    @PrePassivate
    @PostActivate
    @AroundInvoke
    public void callback(InvocationContext context) throws Exception {
        intercept(context);
    }

Second, callback intercept methods are not allowed to throw any exceptions. Again the rationale is that callbacks aren't allowed to throw checked exceptions, so interceptors should be aware of that as well. The trick is we can't simply remove the 'throws Exception' clause without doing any extra work. The InvocationContext.proceed() method throws java.lang.Exception but we can't, so we are forced to take responsibility for it. If we just catch and ignore the exception all hell will break loose, so instead we should at least wrap it as a RuntimeException.

    @PostConstruct
    @PreDestroy
    @PrePassivate
    @PostActivate
    @AroundTimeout
    public void callback(InvocationContext context) {
        try {
            intercept(context);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

We've just made a mistake. Did you see it? If there are several interceptors in the chain and all of them wrap the exception like this, when an actual exception is thrown it will end up wrapped N times -- once per interceptor -- before finally reaching the container. Instead, we should at least check if the exception needs wrapping and hope that other interceptors do the same:

    @PostConstruct
    @PreDestroy
    @PrePassivate
    @PostActivate
    @AroundTimeout
    public void callback(InvocationContext context) {
        try {
            intercept(context);
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else{
                throw new RuntimeException(e);
            }
        }
    }

Now we're done. Summary: all of the above is boilerplate code you need in any well implemented callback-based interceptor.

What have we achieved? Not much.

In terms of user code, it doesn't help you any to have these restrictions. If you wanted special logic for callback-based interceptor methods you can easily put that annotation on a separate method.

In terms of container code, there's little gain as well. Ultimately, most containers use reflection to kick off the interceptor chain. The java.lang.reflect.Method.invoke() method returns Object and throws InvocationTargetException. Restricting users from returning Object and throwing Exception have no real impact on the container code. It's a callback. Ultimately all exceptions, checked or not, go into the log file and no further and return values are simply ignored.

Summary: The restriction on returning void and throwing Exception should be lifted. For backwards compatibility we can just say this former requirement is now optional and allow interceptor signatures of 'Object <method>(InvocationContext c) throws Exception' even if what is being intercepted is a callback.

18 comments:

Unknown said...

20170619 junda
rolex watches,rolex watches,swiss watches,watches for men,watches for women,omega watches,replica watches,rolex watches for sale,rolex replica,rolex watch,cartier watches,rolex submariner,fake rolex,rolex replica watches,replica rolex
ray ban sunglasses
ferragamo outlet
ray ban wayfarer
true religion jeans sale
fitflops
christian louboutin sale
ralph lauren outlet
jordan 4
cheap nfl jerseys

Habib Malik said...

Sarkari Naukri
OBC Bank Recruitment 2018

Danish Ahmed said...

Thanks for sharing this article, now you can check your cut off marks by following below given links

rajasthan post office gds result 2017

north eastern post office gds result 2017

karnataka post office gds result 2017

punjab post office gds result 2017

uttarakhand post office gds result 2017

Danish Ahmed said...

Thanks for sharing this article, now you can check your Time table & Date sheet 2017 by following below given links

ap ssc time table 2017

assam hslc date sheet 2017

bihar board 10th date sheet 2017

cbse board 10th date sheet 2017

ch board 10th date sheet 2017


Habib Malik said...

Kalyani University Routine 2018
Tripura Board Madhyamim Date Sheet 2018
Tripura Board HS Date Sheet 2018
Telangana SSC Date Sheet 2018
Telanagana Intermediate Date Sheet 2018

Habib Malik said...

This information is really good, students can also check Board Time Table 2018

oliviaallan said...

Most people think that online dating is just a waste of time as there are no ways to end up with a beautiful woman. The truth is there are tons of beautiful girls on online dating sites and they are always on the lookout for men to go out with.

http://jrhonest.com/emotional-hook-formula-review/

oliviaallan said...

Emotional Hook Formula program is meant to help women be confident and trust themselves, so they can attract the men they like easily, without exaggerating their behavior.

https://freepdfebookdownload.org/aaron-foxs-emotional-hook-formula/

Unknown said...

The Outback Vision Protocol is an excellent eBook uncovering the exact reasons that result in the vision loss.

http://jrhonest.com/outback-vision-protocol-reviews/

Unknown said...

Increase the size of your penis, such as that of security, is not your main concern when trying to do anything.



http://jrhonest.com/zenith-labss-barbarian-xl-review/

Sharon Wood said...

Norton Toll Free Number
Malwarebytes Contact Number
McAfee Toll Free Phone Number
Avast Antivirus Toll Free Number

Darren Demers said...

In terms of user code, it doesn't help you any to have these restrictions. If you wanted special logic for callback-based interceptor methods you can easily put that annotation on a separate method. shawls for dresses , shawls for women , shawls for sale , black shawl , white shawl , shawl , silver shawl , gold shawl , navy shawl , woolen shawl

Anaminka said...






Men looking for Call Girls in Chanakyapuri usually have a variety of needs that need to be fulfilled. Some want to hire escorts just as a companion, some want them to be their dinner dates or dance floor partners while others may want them to play the role of the sexy girlfriends. Check our other services also..
Female Escorts in Chanakyapuri
Escorts in Chanakyapuri
Escorts Service in Vasant Kunj
Escorts Service in Vasant Kunj
Escorts in Vasant Kunj



No #1 Gurgaon Escorts Service Agency-Gurugram said...




With ourRussian Escorts in Gurgaonand escorts services, you may really improve stage of fun by its quality services different. Sure! This assists its people to victory over all the gloom and depressive disorders from your lifestyle and appeases your delicate wishes specifically.So, you may do a trip at web page and can get your wish suggested with an outstanding woman escort. Check our other services also...
Call Girls in Gurgaon
Escorts in Gurgaon
Escorts in Gurgaon
Female Escorts in Gurgaon
Russian Call Girls in Gurgaon

ncrhotgirls.com said...

Thanks for sharing the article...You write very well...If you need backlinks please reach me on genuinehotelescorts@gmail.com
Call Girls in Jaipur
Call Girls in Jaipur
Call Girls in Jaipur
Call Girls in Delhi
Call Girls in Guwahati
Call Girls in Guwahati
Call Girls in Guwahati
Call Girls in Guwahati
Call Girls in Aerocity
Call Girls in Lucknow

Frank said...

Restricting users from returning Object Buy Essay Online and throwing Exception have no real impact on the container code.

cherry456 said...

The Rajasthan board has conducted 9th class exam from 30th March, . The board examination was conducted in over Rajasthan state. When the board will announce BSER 9th class Textbook 2023 in June, first week, Raj Board 9th Book 2023 then here we will update soon it link. Rajasthan Board 9th Textbook 2023 It BSER 9th Textbook 2023 official site is BSER 9th Textbook 2023

pengiriman murah said...

https://jasapengirimankontainer.com/2022/10/11/kirim-mobil-pakai-kontainer-jakarta-ke-maluku/
https://pengirimanantarpulau.com/ekspedisi-murah-jakarta-ke-maluku/
https://jualbesibetonsurabaya.com/2022/03/31/harga-besi-8-panjang-12-meter-kupang/
https://www.auraabadilogistik.com/ekspedisi-surabaya-pekanbaru/