1 /* 2 * JBoss, Home of Professional Open Source 3 * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual 4 * contributors by the @authors tag. See the copyright.txt in the 5 * distribution for a full listing of individual contributors. 6 * 7 * Licensed under the Apache License, Version 2.0 (the "License"); 8 * you may not use this file except in compliance with the License. 9 * You may obtain a copy of the License at 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package org.jboss.as.quickstarts.servlet.async; 18 19 import javax.inject.Inject; 20 import javax.servlet.AsyncContext; 21 import javax.servlet.annotation.WebServlet; 22 import javax.servlet.http.HttpServlet; 23 import javax.servlet.http.HttpServletRequest; 24 import javax.servlet.http.HttpServletResponse; 25 26 /** 27 * <p> 28 * A simple asynchronous servlet taking advantage of features added in 3.0. 29 * </p> 30 * 31 * <p> 32 * The servlet is registered and mapped to /AsynchronousServlet using the {@link WebServlet} annotation. The 33 * {@link LongRunningService} is injected by CDI. 34 * </p> 35 * 36 * <p> 37 * It shows how to detach the execution of a long-running task from the request processing thread, so the thread is free to 38 * serve other client requests. The long-running tasks are executed using a dedicated thread pool and create the client response 39 * asynchronously using the {@link AsyncContext}. 40 * </p> 41 * 42 * <p> 43 * A long-running task in this context does not refer to a computation intensive task executed on the same machine but could for 44 * example be contacting a third-party service that has limited resources or only allows for a limited number of concurrent 45 * connections. Moving the calls to this service into a separate and smaller sized thread pool ensures that less threads will be 46 * busy interacting with the long-running service and that more requests can be served that do not depend on this service. 47 * </p> 48 * 49 * @author Christian Sadilek <csadilek@redhat.com> 50 */ 51 @SuppressWarnings("serial") 52 @WebServlet(value = "/AsynchronousServlet", asyncSupported = true) 53 public class AsynchronousServlet extends HttpServlet { 54 55 @Inject 56 private LongRunningService longRunningService; 57 58 @Override 59 protected void doGet(HttpServletRequest req, HttpServletResponse resp) { 60 // Here the request is put in asynchronous mode 61 AsyncContext asyncContext = req.startAsync(); 62 63 // This method will return immediately when invoked, 64 // the actual execution will run in a separate thread. 65 longRunningService.readData(asyncContext); 66 } 67 }