Abhilash Abhilash - 23 days ago 12
Java Question

find how many requests are on queue in thread safe spring controller

I am using a spring controller which returns a string from a threadsafe method.
so i have made the controller also thread safe.
I want to know how many request are there in queue simultaneously which are calling to the spring controller

dit dit
Answer

Here is my suggestion how you can solve your issue.

Imagine you have this @Controller:

@Controller
public class MyController {

    @Autowired
    private IMyService service;

    @RequestMapping(value = "/myPathName", method = RequestMethod.GET)
    public String home(HttpServletRequest request, Model model) {

        // you synchronized call
        service.callSynchronized(request, model); 

        return "someJsp";
    }

    // +edit
    @ResponseBody
    @RequestMapping(value = "/queueStatus", method = RequestMethod.GET)
    public String home(HttpServletRequest request) {

        // 
        return "inQueue: " + request.getAttribute("inQueue");
    }
}

Now you can define an interceptor and count the requests before and after execution:

public class RequestsInWorkInterceptor extends HandlerInterceptorAdapter {

    private static final Logger _logger  = LoggerFactory.getLogger(RequestsInWorkInterceptor.class);
    private final AtomicLong counter     = new AtomicLong();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String methodURI = request.getRequestURI();
        long current;
        if("myPathName".equals(methodURI){
            current = counter.incrementAndGet();
            _logger.debug("current {} clients in a queue", current);
        } else {
            current = counter.get(); // just get, no increment
        }

        // +edit: put the count in the request so you can get it in you controller
        request.setAttribute("inQueue", current);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String methodURI = request.getRequestURI();
        if("myPathName".equals(methodURI){
            counter.decrementAndGet();
        }
        super.postHandle(request, response, handler, modelAndView);
    }
}