Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java Filter Singleton

I am implementing a Java enterprise application and declared a Filter for every request, so how does the server tracks this request, do it create a new filter object for every request, or their is only one filter handling all request, in other words are java web filter singletone?

like image 498
Phalguni Mukherjee Avatar asked Feb 12 '14 06:02

Phalguni Mukherjee


People also ask

Are servlet filters singletons?

In any Java servlet container, such as Apache Tomcat, HttpServlet is a singleton class (see MSC07-J. Prevent multiple instantiations of singleton objects for information related to singleton classes). Therefore, there can be only one instance of member variables, even if they are not declared static.

Are Servlet filters thread safe?

Servlets are normal java classes and thus are NOT Thread Safe. But that said, Java classes are Thread safe if you do not have instance variables. Only instance variables need to synchronize. (Instance variable are variables declared in the class and not in within its methods.

What is a singleton in programming?

In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.

What is the method used for applying configuring Web filters in Serviets?

doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks. This is invoked only once when filter is taken out of the service.


1 Answers

First, let's review the definition of Singleton Pattern (emphasis mine):

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.

When you declare a class that implements the Filter interface, it needs a public constructor (usually the default constructor) so the application server could instantiate it. Thus, by doing this, the Filter is not a singleton.

Note that the application server will maintain a single instance per application context e.g. per a deployed web application, but this is not the same as having a singleton. Why? Because you or another programmer can carelessly create an instance of this class (even if it doesn't make use of the instance).

like image 155
Luiggi Mendoza Avatar answered Oct 19 '22 23:10

Luiggi Mendoza