Using Static objects in Java EE - java

I have been having problems with my EE application and I believe I have discovered the root cause- static objects are available across all sessions of a tomcat webapp and do not die. I therefore need to adapt my code so that each session has unique object.
I have several classes which extend a Search.
Search currently has
public static Parser parse;
as a field, and I refer to it through out my code.
Many of my other classes that extend search are created 50 times or so and I simply call super.getParse() whenever I need to use the Parser object. I want to avoid making a new one as it is a slow process.
What is the correct way to create a single Parser object and pass it around my code without it being static?
Really appreciate any advice or guidance.

here what to do:
remove the static from your objects
put the object in the user session
like this every user have his objects in his session
see this may help
HttpSession - how to get the session.setAttribute?

Either use a synchronized accessor if you really need a unique object, or use a thread-local variable.
Note that using a synchronized accessor may decrease the thoughput of your application if all queries need to access that unique object. In that case, a thread-local variable (i.e. not-so unique, but unique session-wide) would be a better solution.
See http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html

You are looking for singleton pattern, you can find reference here
http://www.tutorialspoint.com/java/java_using_singleton.htm

Related

java - how to persist variable in JVM

I have an odd situation where i want to be able to be able to persist a variable in memory.. like a global variable I can pin in the JVM.
Is this possible? I remember doing something similar in college, but can't find it by googling. I have a logic problem that has some artificial constraints that make this the best possible solution.
EDIT 1:
I will need to update the value of the variable.
EDIT 2 :
I appreciate the responses guys. I'm a .net programmer and hadn't used java since college. Thanks again.
Yes, using a static field:
public class GlobalVariableHolder {
public static int globalVariable;
}
Note, however, that this is considered a bad practice and can lead to unexpected results that are hard to debug. The way to not use a global variable is to pass it around as an argument or methods where you need it.
If you are still sure you need this, in order to guard yourself as much as possible, use synchronization. Even better, if the variable is going to be primitive (int, long, etc), you can use AtomicInteger's getAndAdd() or addAndGet() method.
Usually you will end up storing these things in some kind of a global class--a class that is accessible from anywhere and has a controlled number of instances.
Singletons are commonly used for this. If you look up the pattern for a singleton and store your variable in that singleton (add a setter and a getter) you are on your way.
Doing this (as opposed to a public static variable) will give you some level of access control and traceability--for instance you can put debug statements in the getter if you find you are getting unpredictable results.
In the long run setters and getters and singletons are all bad code smells but no where near as bad as a settable public variable.
Later you may want to move the code that manipulates that variable into the singleton object and possibly convert the singleton to something you can fetch via IOC, but having a singleton is a much better place to start than with a public static.
Do you mean something that will exist across multiple invocations of java.exe, or do you mean a single variable that will be the same location in memory regardless of which thread within java.exe access it? Or do you mean a variable that can only be accessed if you're using JRockit? Or maybe just the JVM on your dev machine, but not on another system?
In the first case, you'd need another way to store it, like a config file.
In the second case, like Bozho says, use the static keyword.
In the third case, you'd probably need to use the System class and determine the JVM manufacturer (Assuming that's available from System - I'm not sure off the top of my head, and you'll learn more by looking up the API yourself).
In the fourth case, you're pretty much back to a config file.
Its not going to win any awards but this should work:
package mypackage;
public class MyGlobal {
public static String MY_GLOBAL_VAR = "my variable";
}
Any class within that JVM instance would be able to access MyGlobal.MY_GLOBAL_VAR.
Updated to allow update.

Reading the same ResultSet from multiple threads

In the database, I have a definition table that is read from the application once upon starting. This definition table rarely changes, so it makes sense to read it once and restart the application every time it changes.
However, after the table is read (put into a ResultSet), it will be read by multiple handlers running in their own threads.
How do you suggest to accomplish this?
My idea was to populate a CachedRowSet, and then create a copy of this set (through the createCopy() method) for each handler every time a new request comes.
Do you think this is wise? Does this offer a good performance?
Thanks.
It may be better for you to use the singleton pattern. This would allow you to create a single class that all of your threads could access to get the object that they needed. This could also allow you to not have to shut down your application whenever changes are made. One way to accomplish this is to have a class where you have get and set methods for the information you need. And another class that will give out references of that object.
The class that gives out references could have a private constructor, and a getInstance method that will return a reference to itself to ensure that only one exists. This would also give you some other options regarding what you can do when things change.
Ok, if you control access to the resultSet, and you don't care to update the result set until you restart the application, then i would suggest wrapping the CachedRowSet in a custom class. One possible way to do this is to have a wrapper class that is a singleTon and provide it with getter methods so that other threads or classes for that matter can access it. That way you remove the need to make a copy and remove the dependency on CachedRowSet implementation. Creating a copy would cause unnessary overhead. Imagine, in the way you described above, if you had 1000 threads accessing your result set, you would call createCopy() 1000 times thus creating a 1000 copies of the same resultSet.
I think it is a pattern to read the configuration table into a static data structure (ConcurrentHashMap) and then let the threads to look it up.
You can ensure that there is no write race at startup by populating the reference map from a Servlet.init() - it is guaranteed to execute once per servlet.

Java Session Like Object

I have been developing a project and in this project i have designed my code to do the same job after a specified time interval continuously. The job that wanted to be done has a lot of distinct cycles. The interval is small to execute them normally thus i used threads. Until that point everything is clear for me.
To decrease the process and information transaction i wanted to put an session like object that holds the given data and provide it to any thread at anytime. With this object i plan to not query the same configuration information from database at everytime but if it exists on the session take it else query and store on session.
I'm not sure how to implement this structure.
Regards,
Have you looked at ThreadLocal?
That depends. There are several ways to keep and pass information in Java.
Applicationwide: declare it static and/or load it in a static {}.
Threadlocal: make use of ThreadLocal<T>.
Objects: put data in wrapper objects (javabeans?) which you just create once and pass around as c'tor/method arguments.
In your case I think either 1 or 3 is applicable. A real "session" is usually threadlocal, but your functional requirement ("provide to any thread at anytime", "configuration information") makes me think you're rather looking for an applicationwide constant.

Scope of Static Class Variables in Java

I have a static object defined in my logging class, along the lines of:
class myLoggingClass {
static java.util.Properties properties;
...
...
}
According to my reference book, this means that the properties object is shared by all instances of my class.
I find this definition insufficient. I'm writing a class that is being invoked more than once in each application on our project.
Further, our project uses several web services running in the same tomcat container. Each web service may have multiple threads.
The Java Virtual Machine running on the host may also run one or more web service client applications, which run external to tomcat.
So by this definition, I may have tomcat running multiple web services with threads, each having several objects, which may contain an instance of my class.
There may also be one or two web clients running outside of tomcat, but within the same JVM. Would all of these instances of my class share the same properties object? That would make it JVM-wide.
If the static object is not JVM-wide, does anyone know at what level each one would exist? One per tomcat container? One per web service, and one per standalone web service client application?
The reason: When I update my properties, I'm getting a java.lang.ConcurrentUpdateException from java.util.Properties.
I'm using a static boolean variable to "lock" the properties object when my class updates it, but this is not keeping the exception from occurring.
This leads me to believe that the static object used in my class may not be at the same scoping level as the one used in java.util.Properties... But that's just a guess.
Thanks for any help.
Statics aren't "shared by all instances of a class" - they're unrelated to instances; they belong to the type itself. In particular, static variables are perfectly usable without any instances being created.
That gives a clue as to the scope of statics: they're scoped by the Class object representing the containing class, which is in turn scoped by the ClassLoader that loaded it.
Depending on where the library is placed, the static variable may be JVM-wide or web-application wide - or possibly something in between, if Tomcat supports multiple hosting (I can't remember offhand).
Look at the Tomcat documentation for how the libraries are laid out and how they relate to class loaders. For example, here's the Tomcat 6.0 ClassLoader how-to guide, and the equivalent for 5.5.
How does your Boolean "lock" work? You should really use a proper lock (synchronized) to make sure that every use of the properties object (both read and write, including locking for the whole period during which you iterate through it) is appropriately locked.
Instead of changing the "live" Properties object, have you considered treating that as immutable - so when you want to update the properties, you take a copy, change that, and then make the copy the "live" version? You'd still need to prevent two different threads from making changes at the same time (or you'd lose some) but it's likely to make the reading side a lot easier and more efficient.
You may find that the scope of such a static variable is limited to one per ClassLoader that has loaded your class. I'm not sure how Tomcat arranges its ClassLoaders, so it's hard to say what the extent of the scope will be in that environment.
The likely cause of your ConcurrentModificationException is that you are iterating thru the values/entries of the Properties object in one thread while another modifies it at the same time. You cannot do this.
Can you elaborate on the locking mechanism that you mention here:
I'm using a static boolean variable to "lock" the properties object when my class updates it, but this is not keeping the exception from occurring.
?
Because it doesn't sound as if you are using the built-in locking and synchronization methods in Java.
Something like this should prevent threads from reading the Properties object while another thread updates it:
static Object lockObject = new Object();
...
synchronized(lockObject) {
// access the Properties object
}
Note that you will need to do this every time you access the Properties object, either to read it or modify it.
Also I would never recommend static objects to share data among all instances or static lockObjects - global data is evil - but it sounds as if you need this for some reason.
Could it be a classloader problem where the jar that contains your class is duplicated in each WEB-INF/lib of your different applications?
If so, I would try to add this jar to Tomcat libs and not to the application.

In Java, how can I construct a "proxy wrapper" around an object which invokes a method upon changing a property?

I'm looking for something similar to the Proxy pattern or the Dynamic Proxy Classes, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like the Proxy class in Action Script 3 would be fine.
Here's what I want to achieve in general:
I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.
The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.
During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.
Edit: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.
If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by manipulations on the byte code level though.
Actually, the easiest way to do it is probably by using AspectJ and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe.
How does differential execution work?
Is a question I answered that deals with this.
However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed.
Obligitory links:
Wiki Differential execution
Wiki Callback
Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call.
I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change.
Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at.
Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion).
Hope that helps...
I don't want to intercept method calls before they are invoked on the real object, but
rather I'd like to intercept properties that are being changed
So in fact, the objects you want to monitor are no convenient beans but a resurgence of C structs. The only way that comes to my mind to do that is with the Field Access call in JVMTI.
I wanted to do the same thing myself. My solution was to use dynamic proxy wrappers using Javassist. I would generate a class that implements the same interface as the class of my target object, wrap my proxy class around original class, and delegate all method calls on proxy to the original, except setters which would also fire the PropertyChangeEvent.
Anyway I posted the full explanation and the code on my blog here:
http://clockwork-fig.blogspot.com/2010/11/javabean-property-change-listener-with.html

Categories

Resources