Feedback Form

Async Processing: AsyncContext, Timeouts, and Non-Blocking I/O

Async Processing in Servlets: AsyncContext, Timeouts, and Non-Blocking I/O

Async Processing in Servlets क्या होता है?

जब कोई Servlet request handle करता है, तो normally server उसी thread पर काम करता है जब तक response complete नहीं हो जाता। लेकिन अगर process लंबा हो (जैसे database query, file download या external API call), तो main thread busy हो जाता है। इसी problem को solve करने के लिए Servlet 3.0 में Asynchronous Processing concept लाया गया — जिससे long-running task को background में run कराया जा सके और main thread तुरंत free हो जाए।

Simple Words में समझो

Async Processing का मतलब है कि server request को receive करने के बाद उसे background thread में process करने के लिए छोड़ देता है ताकि main thread दूसरे users की requests को handle कर सके। इससे performance और scalability दोनों improve होते हैं।

AsyncContext Class क्या है?

AsyncContext class Servlet API का core part है जो asynchronous request को manage करता है। जब आप request को async mode में डालते हैं, तो Servlet container एक AsyncContext object return करता है, जिसके through आप background processing, dispatch, या response complete कर सकते हैं।

AsyncContext के Important Methods

  • start(Runnable run): Background thread में task execute करता है।
  • complete(): Async processing खत्म करके response भेजता है।
  • dispatch(): Request को किसी दूसरे Servlet या JSP पर forward करता है।
  • setTimeout(long ms): Timeout set करता है (milliseconds में)।
  • addListener(AsyncListener l): Async events (complete, timeout, error) को सुनता है।

AsyncContext का Basic Example

मान लो हमें किसी heavy calculation या file download task को async में करना है, तो कोड कुछ ऐसा होगा:

@WebServlet(value="/asyncDemo", asyncSupported=true) public class AsyncDemoServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); AsyncContext asyncContext = request.startAsync(); asyncContext.start(() -> { try { Thread.sleep(3000); // simulate long task out.println("Processing done in async thread!"); asyncContext.complete(); } catch (Exception e) { e.printStackTrace(); } }); out.println("Request received, processing in background..."); } }

ऊपर दिए गए example में main thread तुरंत response देता है (“Request received…”), और background thread asyncContext के ज़रिए बाकी काम complete करता है।

Timeout in AsyncContext

Async processing के दौरान अगर task बहुत time ले रहा है, तो उसे automatic terminate करने के लिए timeout set किया जा सकता है। Default timeout 30 seconds होता है। आप इसे setTimeout() method से change कर सकते हैं।

Example:

asyncContext.setTimeout(5000); // 5 seconds

Timeout Event Handling

जब timeout होता है, तो AsyncListener का onTimeout() method call होता है। आप वहाँ error message या log लिख सकते हैं।

asyncContext.addListener(new AsyncListener() { public void onComplete(AsyncEvent event) {} public void onTimeout(AsyncEvent event) { System.out.println("Request timed out!"); } public void onError(AsyncEvent event) {} public void onStartAsync(AsyncEvent event) {} });

Non-Blocking I/O क्या होता है?

Non-blocking I/O का मतलब है कि Input या Output operations करते समय thread को wait नहीं करना पड़ता। यह technique Servlet 3.1 में introduce की गई थी ताकि data read/write करते समय performance improve हो सके।

Blocking बनाम Non-Blocking Difference

Parameter Blocking I/O Non-Blocking I/O
Execution Thread तब तक wait करता है जब तक I/O complete न हो जाए Thread तुरंत free हो जाता है, I/O background में चलता है
Performance Slow (क्योंकि thread block होता है) Fast (क्योंकि multiple requests parallel process होती हैं)
Use Case Small synchronous tasks Large data, streaming, async APIs

Non-Blocking Input Example

Servlet 3.1 में आप ReadListener का use करके non-blocking input stream handle कर सकते हैं।

@WebServlet(value="/nonblocking", asyncSupported=true) public class NonBlockingServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { AsyncContext async = request.startAsync(); ServletInputStream input = request.getInputStream(); input.setReadListener(new ReadListener() { public void onDataAvailable() throws IOException { byte[] buffer = new byte[1024]; int bytesRead = -1; while (input.isReady() && (bytesRead = input.read(buffer)) != -1) { System.out.println("Reading Data..."); } } public void onAllDataRead() throws IOException { response.getWriter().write("All data read successfully!"); async.complete(); } public void onError(Throwable t) { t.printStackTrace(); } }); } }

यहाँ onDataAvailable() method तब call होता है जब data available होता है और thread busy नहीं रहता। इससे multiple clients की requests को एक साथ handle करना possible होता है।

Async Processing के Benefits

  • High Performance: Server threads free रहते हैं, जिससे concurrency बढ़ती है।
  • Scalability: एक ही server अधिक users को handle कर सकता है।
  • Resource Efficiency: Thread blocking नहीं होती, memory consumption कम होता है।
  • Better User Experience: Response जल्दी मिलता है क्योंकि main thread busy नहीं होता।

Real-Life Use Cases

  • External API calls या third-party services
  • Large file upload/download
  • Database report generation
  • Long-running computational tasks

Async Servlets के Best Practices

  • Always handle timeout events properly।
  • Thread-safe operations ही background में करें।
  • AsyncContext.complete() हमेशा call करें, वरना memory leak हो सकता है।
  • Heavy tasks के लिए thread pool use करें।
  • Proper error handling implement करें (AsyncListener के साथ)।

Synchronous vs Asynchronous Servlet Difference

Feature Synchronous Servlet Asynchronous Servlet
Thread Handling Single thread पूरा request handle करता है Main thread request delegate कर देता है background thread को
Performance Low, जब long process हो High, क्योंकि main thread free रहता है
Use Case Quick tasks Long-running tasks जैसे API call या file I/O

Exam Specific Important Points (Quick Notes)

  • Servlet 3.0 से Async Processing feature आया।
  • AsyncContext asynchronous operations को manage करता है।
  • start(), complete(), dispatch() — इसके core methods हैं।
  • Default timeout: 30 seconds (changeable via setTimeout())।
  • Servlet 3.1 में Non-blocking I/O introduce हुआ।
  • ReadListener और WriteListener non-blocking I/O के लिए use होते हैं।
  • AsyncListener के 4 methods होते हैं — onComplete, onTimeout, onError, onStartAsync।
  • Always call asyncContext.complete() after finishing the process।
  • Helps improve scalability and response time।
  • Used for large data handling, API calls, and real-time systems।