Execute method before Business Logic - java

I know about Servlet Filters and Event Listeners but I'm not sure if that's what I need to use.
Let's say I have a method:
Integer count = 0;
public void increment() {
count++;
}
and then a doGet:
public void doGet(HttpServletRequest request, HttpServletResponse response) {
System.out.println(count);
}
When performing a Get request for the first time, I'd expect count=1 and not count=0 because I want the method increment() to be executed first, before any other business logic in the web application.
Also, the count should be different for each user. It should be based on the number of requests a particular user has made.
What can I use to solve this problem?
I would prefer to not use Spring or any other 3rd party library

This all depends on where the count should be available, but you can create an abstract HttpServlet sub class that calls some abstract method to perform logic before handling the request
public abstract class BaseServlet extends HttpServlet {
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// wrap it in try-catch if you need to
prePerformLogic(req, resp);
// call super implementation for delegation to appropriate handler
super.service(req, resp);
}
protected abstract void prePerformLogic(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException;
}
Now your own Servlet implementation will extend from this class. You'll implement it as you see fit. But, as Luiggi has stated in the comments, the example you've posted brings up many possible concurrency issues. A Servlet shouldn't normally have any mutable state.
If you just want to add an counter attribute to the HttpSession, synchronize on the HttpSession, check if an attribute exists. If it doesn't, add one starting at 0. If it does, increment it and add it back as an attribute. You might get better performance with a AtomicInteger, but you need to synchronized the check for the existence of the attribute.
A Filter would probably be more appropriate in that sense, since the Servlet wouldn't have any state anyway.

Related

Is this servlet thread safe?

I have passed the HttpServletRequest to another method in the servlet. Could I keep the servlet thread-safe? Is the below code thread-safe with er() method?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Your session Id: ").append(er(request));
}
public String er(HttpServletRequest request){
return request.getSession().getId();
}
it is perfectly fine, you are not modifying any state within the Servlet itself, the servlet lifecycle creates one instance of the servlet and calls the init() method, any additional requests come through the same instance. so if you don't have any unprotected instance variables, you should be fine.
Because request.getSession() optionally creates a session, the answer is that you may have a race condition where to "simultaneous" calls from the same client may result in different session objects created for that client and consequently, different IDs returned.
See also here

Handle Jersey/JAX-RS REST manually

I'm building an application where I'd like to intercept HTTP requests and decide whether or not to pass them to a JAX-RS implementation for processing.
I basically have a single filter-and-front-controller-servlet combination and would like the servlet to delegate routing either to Jersey or to my "standard" router.
I can see lots of examples of using Jersey as a servlet, or of starting up an HTTP server, but there doesn't seem to be a handy way to take an HttpServletRequest/HttpServletResponse pair and say "here you go Jersey, route this for me".
Am I missing something obvious?
In this case, I think a RequestDispatcher might helps
A RequestDispatcher object can be used to forward a request to another resource, so you can try something like the following:
public class FrontServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext sc = this.getServletContext();
if (someCondition) {
sc.getRequestDispatcher("/jersey/servlet").forward(req, resp);
}else{
sc.getRequestDispatcher("/standard/router").forward(req, resp);
}
}
}

Apache Tomcat Servlet threads not finishing

I've written a servlet deployed in tomcat.
public class myServlet extends HttpServlet {
public int NumberOfThreads = 0;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(NumberOfThreads);
NumberOfThreads++;
....
..a lot of code..
....
NumberOfThreads--;
}
}
Now when I get too many requests the NumberOfThreads keeps rising and never goes down again. My problem is that there is a few tasks that have to be performed by each request before leaving.
I just don't understand why this happens. Is it that some of the threads get lost on the way? I really need each request to say properly goodbye.
Thanks
You are doing it wrong.
System.out.println(ManagementFactory.getThreadMXBean().getThreadCount());
Alternatively, just use JMX/JConsole.
As you're speaking about this taking a long time and requests are being cancelled (in your comment): Yes, the whole doGet will be executed, even when the user cancelled the request: Request cancelling is only on HTTP level. However, when the request is cancelled, the HTTP connection might be closed, resulting in exceptions when you actually want to write to the response's output stream.
Combining the other answers already given:
You'll need to synchronize your modifications of the counter (see didxga's answer)
there's probably a better way to solve your problem (as Ravi Thapliyal states)
use try{ ... } finally { ... } to ensure you actually decrease the counter
make your code more maintainable by moving it out of the servlet into a proper, non-UI, class
Pseudo code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
synchronized(this){NumberOfThreads++;}
doSomething();
} finally {
synchronized(this){NumberOfThreads--;}
}
}
Also, be aware that long-running execution in the actual http connector thread blocks all subsequent http requests - it might be a good idea to trigger background processing and just query that background process in later HTTP requests. That way you can also queue multiple invocations and not start a huge number of background threads at the same time. Keep in mind, there's a limited number of HTTP request handlers.
I'm assuming the try/finally will be your main problem (or an endless loop in your code) - synchronizing will solve rare race conditions, especially as you're speaking of a lot of code executed in this servlet.
The different servlet threads are caching NumberOfThreads. You have to mark it as volatile.
public volatile int NumberOfThreads = 0;
But, I have a feeling that there are better ways of doing what you probably want to achieve with this code.
You need to synchronize modification to NumberOfThreads
public class myServlet extends HttpServlet {
public int NumberOfThreads = 0;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(NumberOfThreads);
synchronized(this){NumberOfThreads++;}
....
..a lot of code..
....
synchronized(this){NumberOfThreads--;}
}
}

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.

How do you to detect the end of a thread via ThreadId?

Talking Java Servlets here... I'm working on creating my own "Per Request Context" and I was looking to tie the "Per Request Context" object to the Thread.currentThread().getId() value.
Instead of passing around this context object everywhere I was planning on checking the current threadid when a user calls a function that is Per Request based and automatically getting the Context object out of a hashtable for that threadId.
I would use the code this like..
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
MyFramework.EnterContext();
try {
// do stuff here that leads to other classes on the same thread
// Access current context via static MyFramework.getCurrentContext()
}
finally { MyFramework.ExitContext(); }
}
However I would like to protect my application automatically from any potential user that does not call ExitContext(). In C# there is an event handler on the thread object for onexit...(think I wrong on this) is there some way to detect or poll when a thread exits? I'm currently storing only the threadId (long).
Any ideas?
unfortunatelly, there is no such feature built in for threads in Java. Besides, thread id is only guaranteed to be unique at any one time, but may be reused eventually when the thread dies (from the docs). however, the servlet framework that you are using may be implementing such feature (just a speculation).
i would recommend you implement a servlet filter, and tell your users to include it in their web.xml. with this you can be sure the client code always gets correctly wraped in your thread context.
A ThreadLocal seems to fit your use perfectly. A ThreadLocal object can provide a way to store a variable per thread. The internal workings of this class are very much of what you describe, it uses a map to give thread-local variables.
Something like this should do the trick:
private static final ThreadLocal<UserContext> userContext = new ThreadLocal<UserContext>();
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
MyFramework.EnterContext();
try {
UserContext context = userContext.get();
//if you used the set method in this thread earlier
//a thread local context would be returned using get
}
finally { MyFramework.ExitContext(); }
}
As for your other problem, you can use an observer pattern and notify when the thread completes its task.

Categories