Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent multiple access of servlet in my application

given below is the url configured as an autosys job .This calls the servlet given below.Can anyone suggest me how to protect this method "psServiceWrapper.processHRFeed();" being called continously with improper data modification by each time this url is pressed continously say 10 times.I want it to be accessed only one thread at a time.

I know i have to use a synchronized method or block ..am not sure on how to..since am not that familiar with threads.

http://mydomain:11000/dorf/HRDORFScriptServlet?script=hrFeed


public class HRDORFScriptServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(HRDORFScriptServlet.class);
private final String script = "script";

@Override
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
    // TODO Auto-generated method stub
    performTask(arg0, arg1);
}

@Override
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
    // TODO Auto-generated method stub
    performTask(arg0, arg1);
}

 /** Execute the servlet.
 * 
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
public void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

    DorfUser dorfUser = DorfSessionUtils.getDorfUser(request.getSession());
    HRDorfFeedServiceWrapper psServiceWrapper = new HRDorfFeedServiceWrapper(dorfUser);
    String reqParam = request.getParameter(script);
    if(reqParam.equals("hrFeed")){
    try{
        psServiceWrapper.processHRFeed();           
    }
    catch(ServiceException se){
        log.error("Error While calling HRFeed Service : "+se.getMessage());
    }
    catch(Exception e){
        log.error("Error While calling HRFeed Service : "+e.getMessage());
    }

    }
 }

}

like image 655
ashwinsakthi Avatar asked Sep 14 '12 10:09

ashwinsakthi


1 Answers

I would move the functionality of psServiceWrapper.processHRFeed() to a simple class that implements Runnable.

public class MyTask implements Runnable
{
    public void run() 
    {
        psServiceWrapper.processHRFeed();
    }
}

Then create an ExecutorService with a fixed thread pool size of 1.

ExecutorService psServiceRunner = Executors.newFixedThreadPool(1);

Everytime the servlet is called, I would post an instance of MyTask to this one.

psServiceRunner.execute(new MyTask());

This will

  1. not block your servlet caller.
  2. ensure that only one servlet can run the method at any point of time.
like image 152
Vikdor Avatar answered Oct 23 '22 01:10

Vikdor