cache object in Jersey resource? - java

I have a Jersey (version 2) resource that, during request handling, creates an object that is used throughout the request.
I would like to cache this object in a thread local storage so that other request handlers that use the same thread could re-use this object.
Is this possible? How is this done in Jersey? I am totally new to Jersey and to Java in general, please help. Can I use javax.ws.rs.container.ContainerRequestContext for this? How? How do I clear the cache?
EDIT:
Specific questions:
If I use javax.ws.rs.container.ContainerRequestContext to cache my objects, at what point can I clear the cache?
Is clearing the cache necessary at all in this case?
Is it a good practice to use thread storage as a cache in servlets?

It is advisable to avoid caching in REST as it is supposed to be stateless. But most simple solution could be to use HttpSession object to store your object and retrieve it later and then dispose it off.
For details you can refer this question:Link

Related

how to ensure thread safety for session attributes

I was writing j2ee code but i am facing a problem with session attribute.
Regarding ensuring of thread safety for session attributes which is being set and accessed in a servlet?
As, i know we can not implement "SingleThreadModel" because this is deprecated in java and also we can not synchronize the doXXXX() method.
I tried to use "SingleThreadModel" but it did not work.
Then How can i ensure it?
Can i synchronize the session object for the same?
please tell me, how to fix it.
You need a session scoped mutex. I.e. synchronize on the session, or better a use case specific object in the session.
You should keep the scope of the mutex as small as possible, as you might result in serializing your requests. I tried it once on a project of mine, where I used Spring's RequestMappingHandlerAdapter.setSynchronizeOnSession() which simply synchronizes on the session for each request. This had a significant impact on a page which displays a list of rendered images. I could watch appearing those images sequentially.

JAX-WS web services thread safety and performance concerns

I understand from a few other posts and my understanding on JAX-WS web services they are not thread-safe. My web service is going to get called by 100's of clients and we need to be able to process around 200 transaction/second.
My web service is going to interact with database to perform its work, if i introduce the synchronized keyword around the code that access the database I essentially will ensure only one thread access the database at a time, I wonder if I will still be able to achieve the required throughput in this case. thanks in advance for your help.
I have been told to actually move the database access work into another class and instaniate that class at the method level that way I won't need to use the synchronized keyword and still achieve thread safety. Is that correct?
If you need transactions and thread safety why aren't you just using EJBs as your JAX-WS endpoints?
We need more info on the application.
In general - for performance in the case you describe + database access I recommend.
Carefully plan your database - index where possible/makes sense, use views, etc...
Try to use a database with a good locking mechanism (lock per row). This way when two requests access different rows, you will not suffer from whole table locking.
Have your transactions as short as possible. If using EJBs - make sure the transaction scope for "read data" methods is not Required or RequiredNew (this might cause opening a transaction).
If you do use synchronization - carefully use the proper lock. Don't be tempted to automatically used "synchronized" as its the easiest to code. Consider using ReaderWriterLock where possible.
Consider using caching where possible, but carefully plan this, so your flows work on "relevant" data.
Start with these directions - I think you will see you can achieve your performance target like this.

Singleton Object Created for each Request

I want to create a singleton object whose scope is basically only the request. This will be used to collect the errors and we need to send error whenever we send the response back.
Can anyone provide pointers toward this thing?
I am also using spring.
I tried using Spring container singleton object scope session or request but still my object is holding values from the earlier request
I am using this error object with AspectJ. Will that may cause problem on static binding?
how about
//sync this code
if(request.getAttribute("someKey") == null){
// create object and set it
}
If you set the Object life cycle in the Spring container to be per request then it should only exist for that HttpRequest.
Generally for direct injection containers like Spring when you set the object life cycle or object scope to be per request then it should create an new instance of the object for each http request that it recieves.
If it is not doing this then I would assume that it is more than likely something to do with your configuration.
Singleton is the defualt for the spring container when creating beans I think so you have to specifically set the object scope to per request.
Bean Scopes
http://static.springsource.org/spring/docs/2.5.x/reference/beans.html
I'm not sure that singleton is what you want here - if two requests arrived concurrently they would share the singleton object, and their errors will get mixed up.
Is it possible to create an object to hold the errors and put that in to a ThreadLocal object. The scope of the object will be constrained by the request, and access to it in the ThreadLocal object is easily achieved from within your application without having to pass a refernce to the object around.
You can use ThreadLocal.

The best place to store large data retrieved by a java servlet (Tomcat)

I have the java servlet that retrieves data from a mysql database. In order to minimize roundtrips to the database, it is retrieved only once in init() method, and is placed to a HashMap<> (i.e. cached in memory).
For now, this HashMap is a member of the servlet class. I need not only store this data but also update some values (counters in fact) in the cached objects of underlying hashmap value class. And there is a Timer (or Cron task) to schedule dumping these counters to DB.
So, after googling i found 3 options of storing the cached data:
1) as now, as a member of servlet class (but servlets can be taken out of service and put back into service by the container at will. Then the data will be lost)
2) in ServletContext (am i right that it is recommended to store small amounts of data here?)
3) in a JNDI resource.
What is the most preferred way?
Put it in ServletContext But use ConcurrentHashMap to avoid concurrency issues.
From those 3 options, the best is to store it in the application scope. I.e. use ServletContext#setAttribute(). You'd like to use a ServletContextListener for this. In normal servlets you can access the ServletContext by the inherited getServletContext() method. In JSP you can access it by ${attributename}.
If the data is getting excessive large that it eats too much of Java's memory, then you should consider a 4th option: use a cache manager.
The most obvious way would be use something like ehcache and store the data in that. ehcache is a cache manager that works much like a hash map except the cache manager can be tweaked to hold things in memory, move them to disk, flush them, even write them into a database via a plugin etc. Depends if the objects are serializable, and whether your app can cope without data (i.e. make another round trip if necessary) but I would trust a cache manager to do a better job of it than a hand rolled solution.
If your cache can become large enough and you access it often it'll be reasonable to utilize some caching solution. For example ehcache is a good candidate and easily integrated with Spring applications, too. Documentation is here.
Also check this overview of open-source caching solutions for Java.

ThreadLocal when using hibernate session/JDO persistenceManager

I trying to understand the best prastice of using ThreadLocal for the above questions. From my understanding the reason of using this is to ensure only one session/pm created for entire application. My question is
is there any impact of using threadlocal like this on clustering application? (example google app engine) ?
if u use "transactional" begin,commit on my application, i do not need to use threadlocal right? since "transaction" already ensure my session open and close properly?
if i need to use "transactional", tx, it should be in threadlocal as well?
why not just use "static" instead of "threadlocal" ?
i interested to hear feedback from you all regarding advantages/disadvantages of using this techinque?
Probably not unless your clustering software can migrate threads between nodes. In this case, you'd need to migrate the thread local data as well.
No. The transaction is attached to the session, so you must keep both in sync. While you can begin a transaction in thread A and commit it in thread B, it's usually very hard to make sure that this work reliably. Therefore: Don't.
Yes.
static is global for the whole application. threadlocal is global per Thread.
Conclusion: If you're a beginner in this area, I suggest to use Spring. The Spring Framework solves many of the problems for you and helps you with useful error messages when something breaks.
Follow the documentation to the letter, especially when it doesn't make sense. Chances are that you missed something important and the Spring guys are right.
ThreadLocal is not used to create one session for the whole application. It is used to create one session for every thread. Every user session will be one thread so the ThreadLocal ensures that every user accessing you web page/ database will get its own database connection. If you use a static singleton pattern every user on the server will use the same database connection and I don't know how that would work out.
The implementation of many of the Transaction engines is actually using ThreadLocal to associate the session state you have with the database to a particular thread. This makes for instance running multiple threads inside of a transaction very difficult.
ThreadLocal is a guarantee of Thread safety but queryable in a semi static way later on by another piece of code. Its a thread global variable. This makes it useful for temporary but session aware information. Another use beyond transactions might be holding onto internal parameters for Authorisation which are then checked with a proxy.

Categories