// Apparently the Servlet API cannot handle asynchronous behavior
// I don't see why the Servlet API shouldn't be extended to
// allow the following class to work correctly.
// Servlets in their current form are inefficient

// Dave Brosius [EMAIL PROTECTED]

import java.io.*;
import java.util.*;
import javax.servlet.*;

public class AsyncServlet extends GenericServlet implements Runnable
{
public static final int NUM_THREADS = 10;
private Thread[] m_Threads = null;
private LinkedList m_Jobs = null;

public void init() throws ServletException
{
m_Jobs = new LinkedList();
m_Threads = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++)
{
m_Threads[i] = new Thread( this );
m_Threads[i].start();
}
}

public void destroy()
{
try
{
for (int i = 0; i < NUM_THREADS; i++)
m_Threads[i].interrupt();
for (int i = 0; i < NUM_THREADS; i++)
m_Threads[i].join();
m_Jobs.clear();
m_Jobs = null;
}
catch (Exception e)
{
}
}

public void service( ServletRequest request, ServletResponse response )
{
ReqResp rr = new ReqResp( request, response );
synchronized( m_Jobs )
{
m_Jobs.addFirst( rr );
m_Jobs.notify();
}
}

public void run()
{
Thread t = Thread.currentThread();
while (!t.interrupted())
{
try
{
ReqResp rr = null;
synchronized( m_Jobs )
{
if (m_Jobs.size() > 0)
rr = (ReqResp)m_Jobs.removeLast();
else
m_Jobs.wait();
}

if (rr != null)
{
t.sleep(5000);//simulate work
ServletResponse response = rr.getResponse();
PrintWriter pw = response.getWriter();
pw.println("<HTML>");
pw.println("<BODY>");
pw.println("Hello World");
pw.println("</BODY>");
pw.println("</HTML>");
pw.flush();
pw.close();
}
}
catch (InterruptedException ie)
{
break;
}
catch (Exception e)
{
System.out.println("Exception:" + e.getClass ().getName() + " " +
e.getMessage());
}
}
}
}

class ReqResp
{
private ServletRequest m_Request;
private ServletResponse m_Response;

public ReqResp( ServletRequest req, ServletResponse resp )
{
m_Request = req;
m_Response = resp;
}

public ServletRequest getRequest()
{
return m_Request;
}

public ServletResponse getResponse()
{
return m_Response;
}
}

___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".

Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html

Reply via email to