Spring: ‘request’ scoped beans into the background thread

It is known that there no way to deal with request-scoped beans outside of request thread. But sometimes it is required to check such beans for existence, because the algorithm should works whether is it a request context or not. The wondering thing is that such bean is not null even in background thread. So we need something more than bean != null.

The working way to do that is:

@Autowired(required = false)
private RequestScopedBean requestScopedBean;

private RequestScopedBean getRequestScopedBean() {
    if (AopUtils.isAopProxy(requestScopedBean) && 
        requestScopedBean instanceof Advised) {
        try {
            Advised advised = (Advised) this.requestScopedBean;
            TargetSource targetSource = context.getTargetSource();
            Object target = targetSource.getTarget();
            return (RequestScopedBean)target;
        } catch (Exception e) {
            // do nothing
        }
    }
    return null;
}

Looking for conventional approach…

Spring: ‘request’ scoped beans into the background thread

MemoryMeter & RamUsageEstimator

There are two tools working in the different ways but giving the same result.

https://github.com/jbellis/jamm and https://github.com/dweiss/java-sizeof

The first one is using a java.lang.instrument.Instrumentation, the second one do it in the old-fashioned way (based on types info).

In case you are using MemoryMeter:

-javaagent:/Users/nikolay/.m2/repository/com/github/jbellis/jamm/0.3.1/jamm-0.3.1.jar

should be passed to VM options

 

MemoryMeter & RamUsageEstimator