0

I asked this question about multithreading in servlet, and many people suggest using a static variable.

If I set a static variable and I need to initialize it. For example public static Semaphore permits;

At first, I tried to initialize it in the init() method of a filter associated with the servlet:

public void init(FilterConfig conf) throws ServletException {
        // TODO Auto-generated method stub
    try{
            limit = Integer.parseInt(conf.getInitParameter("filterLimit"));
            permits = new Semaphore(limit);
    }catch(Exception ex){
            conf.getServletContext().log("Fail to set the parameter : permits.");
            throw new ServletException(ex.getMessage());
    }   


}

Then I thought that with so many threads, every threads executing the init() method will initialize the semaphore, it should be not working.

Then I tried to use a static initializer:

static{
        try{
            limit = Integer.parseInt(conf.getInitParameter("filterLimit"));
            permits = new Semaphore(limit);
        }catch(Exception ex){
            conf.getServletContext().log("Fail to set the parameter : permits.");
            throw new ServletException(ex.getMessage());
        }

 }

But I cannot use the conf object as it is passed from the init() method. I want to get the limit number from web.xml, instead of hardcoding it. Any idea to solve this?

Community
  • 1
  • 1
lamwaiman1988
  • 3,729
  • 15
  • 55
  • 87
  • It is definitely not true that every thread calls `init()` method. It's called only once by the container directly after servlets instantiation. Please read this to understand how servlets work: http://stackoverflow.com/questions/3106452/java-servlet-instantiation-and-session-variables/3106909#3106909 – BalusC Jun 02 '11 at 11:16

2 Answers2

4

Then I thought that with so many threads, every threads executing the init() method will initialize the semaphore, it should be not working.

I don't understand. Your init() method should be called by the Servlet container, only once. How are you using these filters / servlets? Is the Thread created within the servlet, or is it created outside the servlet?

If it's created inside the servlet, it should be fine to use a variable created in the init() method.

1

Simply check limit for null before initializing.

Alex Gitelman
  • 24,429
  • 7
  • 52
  • 49