开发者

How can I initialize this semaphore

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 a开发者_开发问答s 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?


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.


Simply check limit for null before initializing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜