Why did Servlet.service() for servlet jsp throw this exception?

后端 未结 5 1510
闹比i
闹比i 2020-11-27 17:34

I get the following error, what could be the problem?

My context descriptor:




        
5条回答
  •  误落风尘
    2020-11-27 17:57

    I had this error; it happened somewhat spontaneously, and the page would halt in the browser in the middle of an HTML tag (not a section of code). It was baffling!

    Turns out, I let a variable go out of scope and the garbage collector swept it away and then I tried to use it. Thus the seemingly-random timing.

    To give a more concrete example... Inside a method, I had something like:

    Foo[] foos = new Foo[20];
    // fill up the "foos" array...
    return Arrays.asList(foos); // this returns type List
    

    Now in my JSP page, I called that method and used the List object returned by it. The List object is backed by that "foos" array; but, the array went out of scope when I returned from the method (since it is a local variable). So shortly after returning, the garbage collector swept away the "foos" array, and my access to the List caused a NullPointerException since its underlying array was now wiped away.

    I actually wondered, as I wrote the above method, whether that would happen.

    The even deeper underlying problem was premature optimization. I wanted a list, but I knew I would have exactly 20 elements, so I figured I'd try to be more efficient than new ArrayList(20) which only sets an initial size of 20 but can possibly be less efficient than the method I used. So of course, to fix it, I just created my ArrayList, filled it up, and returned it. No more strange error.

提交回复
热议问题