Web applications: servlet thread safety using singleton pattern - java

I'm looking to hopefully get into web application programming using Java, coming from a PHP/Laravel background (I have some Java experience having studied it around about 8 years ago at university).
I've been playing around for a while and feel fairly comfortable with most of the foundational concepts such as Servlets and Servlet containers as well as some popular web server/servlet container technologies used such as Jetty, Tomcat etc. I've also tried to do quite a bit of research into Java EE.
Now since I want to build up my knowledge on the subject, I don't want to use any frameworks, in fact I would like to look to build my own as a learning exercise. However, I've also looked quite a bit into some of the frameworks around, such as Spring MVC, Struts, Play and Vaadin etc.
So I've got a Maven project set up, I have a web.xml file set up pointing at a servlet that I have created and I am looking to build an entry point into my "framework".
src/main/webapp/WEB-INF/web.xml
<servlet>
<servlet-name>Application</servlet-name>
<servlet-class>com.mypackage.Application</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
src/main/java/com/mypackage/Application.java
package com.mypackage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Application extends HttpServlet {
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
}
}
So now I want to make my own IoC container that uses the singleton pattern (I know this is usually discouraged and is considered an anti-pattern), so it is easy to access it from other parts of my application:
src/main/java/com/mypackage/Container.java
package com.mypackage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Container {
private static Container instance;
public static Container make(HttpServletRequest request, HttpServletResponse response) {
return instance = new Container();
}
public static Container getInstance() {
if (instance == null) {
// Throw an exception
}
return instance;
}
private Container(HttpServletRequest request, HttpServletResponse response) {
// ...
}
}
I want to create a Container object for every request/response cycle (or every servlet) as the entry point to my application. So I would look to do something like this:
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Container container = Container.make(request, response);
// Do stuff with container and eventually respond to the client
}
Now I know that thread safety is a concern when it comes to servlets, and properties on the servlet instance are shared among threads, but my question relates specifically to the Container object I'm creating using the singleton pattern and thread safety.
Is my current approach considered to be thread safe? If not, why, and how can I make it thread safe? Bear in mind that don't actually want my Container instance to be shared among each thread and would like a separate container for each incoming request/response.
Would it be thread safe (or a recommended approach) to create a new object inside the service method of the servlet class and then have that new object create an instance of the Container? e.g.
public class Something {
public Something(HttpServletRequest request, HttpServletResponse response) {
Container.make(request, response);
}
}
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Something something = new Something(request, response);
// Do stuff with container and eventually respond to the client
}
Finally, would I be correct in assuming that the issue of thread safety arises due to the servlet container re-using servlet instances? As per the Java EE documentation:
The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.
If an instance of the servlet does not exist, the web container
Loads the servlet class.
Creates an instance of the servlet class.
Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.

Creating an instance in the servlet means that it is not thread-safe as a servlet instance is reused.
A Singleton or ApplicationScoped object will only have one copy across your entire application. If you want to make sure that there is only one instance of the object then annotate the class with #ApplicationScoped:
#ApplicationScoped
public class Something {
//do stuff
}
Then in the servlet inject it:
public class SomeServlet extends HttpServlet {
#Inject
Something obj;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) {
//do stuff
}
}
If instead you want the class to you are using to be unique per request then make your class RequestScoped instead. Like so:
#RequestScoped
public class Something {
//do stuff
}
For more information see the CDI tutorial at https://docs.oracle.com/javaee/6/tutorial/doc/giwhl.html. Note that this will require using an application server that has CDI i.e. Payara and not just a servlet container.

Related

Spring REST service using variable URL

I am trying to develop a RESTful app with Spring. The REST service must be parametrized in a database, I mean, a generic Service that can change the whole URL from a database info doing the same work but pointing to differents URL directions.
I was searching for info related for ages. Does anyone know about useful tutorial?
is it possible to do?
Thanks everyone!
You're better off creating a simple Servlet that will listen to a static root url and respond dynamically according to the database value.
public class Config {
public static String restPath = "valueReadFromDB";
}
#WebServlet("/appName")
public class AppServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
if (req.getURI().contains(Config.restPath) {
// add your logic
}
}
}
You can call this like so: http://your.host.name/appName/dynamicUrlReadFromDB
Don't blindly attempt to use Spring just because it is cool or fashionable. Sticking to the basics can always yield excellent results and allows for fine-grained control of your application something that Spring cannot always do.

How servlets container instantiates external classes used by servlets?

I know one Servlets instance is shared by multiple threads for handling concurrent requests. Inside the servlets, I will call other thread-safe classes: ExternalClassOne which in turn calls ExternalClassTwo.
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ExternalClassOne cOne = new ExternalClassOne();
cOne.doSomething();
//doSomething() will also use other classes like ExternalClassTwo, ExternalClassThree...
}
}
I have some questions:
How many instances of the classes ExternalClassOne, ExternalClassTwo will be created?
If they are created per thread for each request (e.g., 100 concurrent requests = 100 instances of ExternalClassOne), does making them singleton increase the performance? Does Tomcat have any "magic" to reuse thread-safe instance where possible?
Instances are created on each execution of new, as already stated in the comment above.
Careful with singletons: To obtain the instance needs a synchronized method invocation, and this ruins the responsiveness of your application.
Tomcat does not provide any such means afaik, but the Java library. You may use ThreadLocals.
Otherwise, create the (thread-safe) classes in a ContextListener on application startup and put them in the app context, so each servlet can get them from there.

Java servlet annotations

Is there any way to use pure Java servlets not spring mvc request mapping to map a URL to a method?
something like:
#GET(/path/of/{id})
It's also possible with "plain vanilla" servlets (heck, Spring MVC and JAX-RS are also built on top of servlet API), it only requires a little bit more boilerplate.
#WebServlet("/path/of/*")
public class PathOfServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getPathInfo().substring(1);
// ...
}
}
That's all. Thanks to the new Servlet 3.0 #WebServlet annotation, you don't need any web.xml entry.
See also:
Our Servlets wiki page

A Spring MVC controller that delegates to a Servlet

One of my projects uses Spring MVC to handle URL mappings and dispatch logic. I have now to use a third party library which uses its own HttpServlet as the main entry point for its functionalities, but as it's an optional drop-in replacement for another library I can't just put the <servlet> declaration in the web.xml: I'd rather use a Controller and Spring profiles to switch between such implementations without having to edit the web.xml.
Is there anything offered OOTB by Spring to handle such cases? I don't seem to find it right away.
Thanks in advance!
Since registering the third party servlet in your web.xml is a no-go, I think your best bet would be to create a singleton instance of the servlet in your ApplicationContext, and then create a custom view that delegates to said servlet's service method.
You can see an example of custom views in action in this tutorial.
Answering my own question here just in case my approach can be useful to others.
There are two key factors I needed to consider:
the proper initialization of the servlet
give the servlet full control over the HTTP layer (e.g. setting HTTP headers, etc)
In my specific case there's no need for properly handling the servlet destruction, as it's a no-op.
I ended up writing a dedicated Controller, to be instantiated only if a specific Spring profile is activated, which takes care of instantiating and initializing the Servlet. Then, all the requests will be directly handled in a void handler method, as follows:
public class ServletDelegatingController implements ServletConfig {
private final DelegateServlet delegate = new DelegateServlet();
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
delegate.service(request, response);
}
// properly initializes the servlet
public void setServletConfig(ServletConfig servletConfig) {
try {
delegate.init(servletConfig);
} catch (ServletException e) {
throw new IllegalStateException("Failure while initializing the servlet", e);
}
}
}
The delegating-servlet.xml for the DispatcherServlet looks like the following:
<beans profile="custom">
<bean id="cmisServiceFactory"
class="com.foo.ServletDelegatingController"/>
</beans>

Proper scope for App Engine services

What is the proper scope for App Engine services when creating a servlet: static, instance, or local? And what are the implications of each? It seems like you should want to use them in as wide a scope as possible, to avoid the overhead of re-creating (or re-retrieving) them, but I wonder as to whether this will cause improper reuse of data, especially if <threadsafe>true</threadsafe>.
Examples of each scope are provided below. MemcacheService will be used in the examples below, but my question applies to any and all services (though I'm not sure if the answer depends on the service being used). I commonly use MemcacheService, DatastoreService, PersistenceManager, ChannelService, and UserService.
Static scope:
public class MyServlet extends HttpServlet {
private static MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService();
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
memcacheService.get("x");
}
}
Instance member:
public class MyServlet extends HttpServlet {
private MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService();
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
memcacheService.get("x");
}
}
Local scope:
public class MyServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService();
memcacheService.get("x");
}
}
GAE is a distributed system where all of it's services run on separate servers. So when you invoke a service it internally serializes the request (afaik with protocol buffers) sends it to the server running the service, retrieves the result and deserializes it.
So all of *Service classes are basically pretty thin wrappers around serialization/deserialization code. See for example source of MemcacheService.
About scope: there is no need to optimize on *Service classes as they are pretty thin wrappers and creating them should take negligible time compared to whole service roundtrip.

Categories