Classloader mystery in Tomcat + Spring environment - java

I have two java static methods for class A:
private static String value;
public static void setValue(String str) {
value = str;
}
public static String getValue() {
return value;
}
sounds simple. I call A.setValue("someValue"), then in some other classes which loaded by spring application context, I call A.getValue(), I am getting null back; while at the same time, in the original place, the A.getValue() still returns "someValue".
So it seems to me there are two instances of the same java class in the tomcat JVM. Is there some way to make sure there is only one instance for one java class?
Thanks.

Perhaps you actually don't have a singleton here and are seeing the class A loaded by two different class loaders? One solution in this case would be to have the Spring bean created (not as prototype) and injected into the two places you are using it - so the framework manages the life cycle of the singleton. If this is still a problem you might want to consider the design of the above, specifically with regards to concurrent access.

Related

How to get a global reference of an array without knowing its size beforehand?

I'm stuck in a situation, where I need a global reference of an array but I get to know it's size only after the user enters it.
I've tried to make another class and do something, but still the problem remains the same, I can only declare local array since I don't have it's size beforehand.
What can be done?
You could use a Provider that holds the array and gives Access to it via a static getter-method. Like so:
public class MyGLobalArrayProvider {
private static String[] myGlobalArray;
public static String[] getGlobalArray() {
return myGlobalArray;
}
public static void doSomeUpdateMagic() {…}
}
Generally I would prefere a solution using Dependency Injection with Guice or Spring. In that case you would inject a singleton Service that holds the array. This would decouple your Code which is not only usefull for testing but also leads to better maintainabilty.
Another classic approach would be the Singleton-Pattern if the DI-Approach is inappropriate heavy.

Why declare self static instance of a class

I sometimes see that people create self instance for example:
public class Example extends Service
{
private static Example mInstance = null;
public void onStart( Intent aIntent, int aStartId )
{
mInstance = this;
.
.
.
}
}
What is the purpose of this?
This is called the Singleton design pattern. Singletons are used when there is going to be a single instance of an object performing operations on non-static data.
See here.
In addition to what other answers put about Singleton pattern, self instances may be used as constants. That's the case of the Color class, that defines an instance for each of the common colours.
http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html
An Android Service (sub)class cannot be a singleton since the framework requires access to a default constructor for the class. The only reason I can think of for keeping a static reference to the (last) instance for which onStart was called is to simplify some internal code that may happen to reside in static methods.
Considering that onStart was deprecated a long time ago (as of API level 5), this is most likely an example of bad coding style from early days of Android.
So that other classes can get an instance and call instance methods on the object. Its frequently used with the Singleton pattern. And for Services and Activities in Android it's a very bad idea- it keeps a reference to the Activity/Service around after it ends, which will cause a memory leak.
In a thread-unsafe singleton pattern implementation, you would have a private constructor, and a public static getInstance method initializing that instance if necessary and returning it.
Here's an example. Note that it is advised to leverage the commodity of a single-element enum instead of the code below, to achieve a "true" singleton.
public class MyThreadUnsafeSingleton {
private static MyThreadUnsafeSingleton instance;
private MyThreadUnsafeSingleton() {
//TODO some ctor logic
}
public static MyThreadUnsafeSingleton getInstance() {
if (instance == null) {
instance = new MyThreadUnsafeSingleton();
}
return instance;
}
}
Final note, there is a variation of the above pattern that is thread-safe across a single classloader through the usage of a nested "holder" class, but that's quite out of scope.
If it has a private default constructor, it's probably a singleton.
If it doesn't, it's something weird.
This sort of layout forces all object instances of this class to share data, regardless of when they are instantiated. The object instance on which OnStart is called will become the underlying data source for any references to this class, regardless of when they were declared or instantiated (before or after OnStart), and regardless of what thread they were created on.
Of course it is always possible there are members of the class that don't bother with mInstance.Member and use this.Member instead. That sort of mixing and matching would probably end up being disastrous.
It's hard to imagine the specific use for this but my guess is that the class is an abstraction of some stateful resource that is global with respect to the process, e.g. a form/window or a web service client that caches its credentials. Could be anything though.
If this code was written around 2003-2005 (early c# days) I'd guess that it is a sloppy implementation of a Singleton-- it was sort of in vogue back then as design patterns were becoming a thing and Singleton was the example in all the textbooks. Turns out it's a horrible pattern for dependency injection and mocking, so these days this pattern doesn't get used as much.
This paradigm is often used for objects that are heavy or slow to construct and only one is needed.
public class Server {
private static Server server = null;
// Stop them making their own.
private Server () {
// Heavyweight stuff.
}
public static Server getServer () {
if ( server == null ) {
// Heavy constructor.
server = new Server();
}
return server;
}
}
In a multi-thread environment it is usually combined with the singleton design pattern.

How can I create an object of a class that can remain in memory and be accessible to all other classes?

I parse a html document and save the data in class. how can I access that class from different classes without initiating it again because I want to use one version of that class
Why dont you set it to a static variable?
public static HtmlData data;
private void parse() {
···
data = result;
}
// now you can use the data object anywhere in your code by calling HtmlData.data
As said in your comments, a singlton would be the way to go. A singleton is holding and managing its own instance, so that you can return this same instance to everyone asking for it.
catchword 'dependency injection', best practice, rather than calling the factory via static access directly, is holding the instance in a private property within the class you need it and "inject the dependency" with public setter in a centralized way, while initializing your application.

Can this Java singleton get rebuilt repeatedly in WebSphere 6?

I'm trying to track down an issue in our system and the following code worries me. The following occurs in our doPost() method in the primary servlet (names have been changed to protect the guilty):
...
if(Single.getInstance().firstTime()){
doPreperations();
}
normalResponse();
...
The singleton 'Single' looks like this:
private static Single theInstance = new Single();
private Single() {
...load properties...
}
public static Single getInstance() {
return theInstance;
}
With the way this is set to use a static initializer instead of checking for a null theInstance in the getInstance() method, could this get rebuilt over and over again?
PS - We're running WebSphere 6 with the App on Java 1.4
I found this on Sun's site:
Multiple Singletons Simultaneously Loaded by Different Class Loaders
When two class loaders load a class,
you actually have two copies of the
class, and each one can have its own
Singleton instance. That is
particularly relevant in servlets
running in certain servlet engines
(iPlanet for example), where each
servlet by default uses its own class
loader. Two different servlets
accessing a joint Singleton will, in
fact, get two different objects.
Multiple class loaders occur more
commonly than you might think. When
browsers load classes from the network
for use by applets, they use a
separate class loader for each server
address. Similarly, Jini and RMI
systems may use a separate class
loader for the different code bases
from which they download class files.
If your own system uses custom class
loaders, all the same issues may
arise.
If loaded by different class loaders,
two classes with the same name, even
the same package name, are treated as
distinct -- even if, in fact, they are
byte-for-byte the same class. The
different class loaders represent
different namespaces that distinguish
classes (even though the classes'
names are the same), so that the two
MySingleton classes are in fact
distinct. (See "Class Loaders as a
Namespace Mechanism" in Resources.)
Since two Singleton objects belong to
two classes of the same name, it will
appear at first glance that there are
two Singleton objects of the same
class.
Citation.
In addition to the above issue, if firstTime() is not synchronized, you could have threading issues there as well.
No it won't get built over and over again. It's static, so it'll only be constructed once, right when the class is touched for the first time by the Classloader.
Only exception - if you happen to have multiple Classloaders.
(from GeekAndPoke):
As others have mentioned, the static initializer will only be run once per classloader.
One thing I would take a look at is the firstTime() method - why can't the work in doPreparations() be handled within the singleton itself?
Sounds like a nasty set of dependencies.
There is absolutely no difference between using a static initializer and lazy initialization. In fact it's far easier to mess up the lazy initialization, which also enforces synchronization. The JVM guarantees that the static initializer is always run before the class is accessed and it will happen once and only once.
That said JVM does not guarantee that your class will be loaded only once. However even if it is loaded more than once, your web application will still see only the relevant singleton, as it will be loaded either in the web application classloader or its parent. If you have several web application deployed, then firstTime() will be called once for each application.
The most apparent things to check is that firstTime() needs to be synchronized and that the firstTime flag is set before exiting that method.
No, It won't create multiple copies of 'Single'. ( Classloader issue will be visited later )
The implementation you outlined is described as 'Eager Initialization' by in Briant Goetz's book - 'Java Concurrency in Practice'.
public class Single
{
private static Single theInstance = new Single();
private Single()
{
// load properties
}
public static Single getInstance()
{
return theInstance;
}
}
However, the code is not you wanted. Your code is trying to perform lazy-initialization after the instance is created. This requires all the client library to perform 'firstTime()/doPreparation()' before using it. You are going to rely on the client to do right thing which make the code very fragile.
You can modify the code as the following so there won't be any duplicate code.
public class Single
{
private static Single theInstance = new Single();
private Single()
{
// load properties
}
public static Single getInstance()
{
// check for initialization of theInstance
if ( theInstance.firstTime() )
theInstance.doPreparation();
return theInstance;
}
}
Unfortunately, this is a poor implementation of lazy initialization and this will not work in concurrent environment ( like J2EE container ).
There are many articles written about Singleton initialization, specifically on memory model. JSR 133 addressed many weakness in Java memory model in Java 1.5 and 1.6.
With Java 1.5 & 1.6, you have several choices and they are mentioned in the book 'Effective Java' by Joshua Bloch.
Eager Initialziation, like the above [EJ Item 3]
Lazy Initalization Holder Class Idiom [EJ Item 71]
Enum Type [EJ Item 3]
Double Checked Locking with 'volatile' static field [EJ Item 71]
Solution 3 and 4 will only work in Java 1.5 and above. So the best solution would be #2.
Here is the psuedo-implementation.
public class Single
{
private static class SingleHolder
{
public static Single theInstance = new Single();
}
private Single()
{
// load properties
doPreparation();
}
public static Single getInstance()
{
return SingleHolder.theInstance;
}
}
Notice that 'doPreparation()' is inside of the constructor so you are guarantee to get the properly initialized instance. Also, you are piggying back on JVM's lazy class loading and do not need any synchronization 'getInstance()'.
One thing you noticed that static field theInstance is not 'final'. The example on Java Concurrency does not have 'final' but EJ does. Maybe James's can add more color to his answer on 'classloader' and requirement of 'final' to guarantee correctness,
Having said that, there are a side-effect that with using 'static final'. Java compiler is very aggressive when it sees 'static final' and tries to inline it as much as possible. This is mentioned on a blog posting by Jeremy Manson.
Here is a simple example.
file: A.java
public class A
{
final static String word = "Hello World";
}
file: B.java
public class B
{
public static void main(String[] args) {
System.out.println(A.word);
}
}
After you compile both A.java and B.java, you change A.java to following.
file: A.java
public class A
{
final static String word = "Goodbye World";
}
You recompile 'A.java' and rerun B.class. The output you would get is
Hello World
As for the classloader issue, the answer is yes, you can have more than one instance of Singleton in multiple classloaders. You can find more information on wikipedia. There is also a specific article on Websphere.
The only thing I would change about that Singleton implementation (other than not using a Singleton at all) is to make the instance field final. The static field will be initialised once, on class load. Since classes are loaded lazily, you effectively get lazy instantiation for free.
Of course, if it's loaded from separate class loaders you get multiple "singletons", but that's a limitation of every singleton idiom in Java.
EDIT: The firstTime() and doPreparations() bits do look suspect though. Can't they be moved into the constructor of the singleton instance?
No - the static initialization of the instance will only ever be done once. Two things to consider:
This is not thread-safe (the instance is not "published" to main memory)
Your firstTime method is probably called multiple times, unless properly synchronized
In theory it will be built only once. However, this pattern breaks in various application servers, where you can get multiple instances of 'singleton' classes (since they are not thread-safe).
Also, the singleton pattern has been critized a lot. See for instance Singleton I love you, but you're bringing me down
This will get only loaded once when the class is loaded by the classloader.
This example provides a better Singleton implementation however, it's as lazy-loaded as possible and thread-safe.
Moreover, it works in all known versions of Java.
This solution is the most portable across different Java compilers and virtual machines.
public class Single {
private static class SingleHolder {
private static final Single INSTANCE = new Single();
}
private Single() {
...load properties...
}
public static Single getInstance() {
return SingleHolder.INSTANCE;
}
}
The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile and/or synchronized).
It's not mandatory for the single instance to be final (it's not a good idea at all indeed, because this will avoid you to switch it's behaviour using other patterns).
In the code below you can see how it gets instantiated only once (first time you call the constructor)
package date;
import java.util.Date;
public class USDateFactory implements DateFactory {
private static USDateFactory usdatefactory = null;
private USDateFactory () { }
public static USDateFactory getUsdatefactory() {
if(usdatefactory==null) {
usdatefactory = new USDateFactory();
}
return usdatefactory;
}
public String getTextDate (Date date) {
return null;
}
public NumericalDate getNumericalDate (Date date) {
return null;
}
}

Difference Between Using Static Fields That Uses Getter And Setter And Static Fields That Are Declared Public

I searched about best ways to hold/share data that are to be used globally and as expected I found a lot of answers. One of the ways that caught my attention is by using static fields. However, the static field way stated there was like this:
public class DataHolder
{
private static String dataString;
public static String getDataString
{
return dataString;
}
public static void setString(String dataString)
{
this.dataString = dataString;
}
}
But I am always doing it this way:
public class DataHolder
{
public static String dataString;
}
I am just wondering isn't the latter much more easier than the first? Because I don't have to set any getter and setter methods. And I don't see any difference between the two. So why not recommend the second one?
I was also told before that doing my way would result to memory leak problem sometimes. But won't the first solution lead to memory leak issues?
Your question about memory leaks
I want to start off by saying there will be no memory leak issues here. In fact, it would be exactly the opposite of memory leaks in both cases (they're the same in this respect). You can have only one instance of a String for the DataHolder class (since it is static, it does not belong to any DataHolder instance).
Imagine it was not static:
public class DataHolder
{
String dataString;
}
this means that for every time you do new DataHolder(), you will have a separate instance of a String. With your static dataString, there will only ever be one instance.
Getters and Setters and Synchronization
The reason why your implementation is bad is because it is not thread safe, as Piyush Mittal pointed out. He didn't get into any details though, so I want to add my two cents.
You can't say that just because you only expect it to be used in a single thread that it will only be used in a single thread. The Swing thread is a great example of this, where there is only ever one thread that handles the UI. You would expect in this case that only one thread exists, and it is OK to do this. However, any background work must be done in a SwingWorker thread, so creating a SwingWorker thread here to do that will provide a data race opportunity because now there are two threads. You should always have getters and setters for static variables for this reason.
That being said, the code snippet you provided is exactly the same between your two examples (with the small difference of generating a new stack frame for the new function) because there is no synchronization. You want to do this:
public class DataHolder{
private static String dataString;
public static String getDataString(){
synchronized(DataHolder.class){
return DataHolder.dataString;
}
}
public static void setString(String dataString){
synchronized(DataHolder.class){
DataHolder.dataString = dataString;
}
}
}
I did change some things about your code. The first and most obvious is there is no this keyword used for static variables. As I hinted at before, because its static it does not belong to any instance. 'this' is not a thing in a static context.
The other thing I did was put the synchronized inside of the method. I did this for two reasons. The first was preference; some people prefer to keep synchronized out of the function signature so it is obfuscated from the caller, so they don't make assumptions because the function is synchronized. That is preference. The other reason I did this, is because I wanted to make it obvious that when you synchronize a function in the signature, this is how it actually will look 'under the hood'. As mentioned, since there is no 'this', it will actually synchronize on the class itself.
I think you could probably use some reading about the static keyword. I think your confusion is coming from the fact that you don't understand it, and you're trying to answer a question about getters and setters for the static variable before understanding statics themselves. Here is a link I found with a quick google search that might get you started:
http://www.javatpoint.com/static-keyword-in-java
don have much idea about memory leaks.
But: multiple parallel requests - multiple threads, you surely have a threading issue here - this is not thread-safe unless you take care of (e.g. use synchronized).
I would much prefer the getter/setters, rather than a public field.
That sort of encapsulation allows you to modify the types of properties without breaking the code of those using it.
What if you decided to create a Data type, rather than storing it as a String? (for increased type safety).
With a public field, it's not possible. But using getter/setters, you can perform the parsing needed to allow this:
class SomeClass {
private static Data data;
public static void setData(String data) {
data = new Data(data);
}
public static String getData() {
return data.toString();
}
}
class Data {
private String data;
public Data(String data) {
this.data = data;
}
public String toString() {
return data;
}
}
It's not a memory leak problem, as it has nothing to do with allocating memory. There may be some inconsistency between threads when using that data, since it is not thread-safe, but any leaking will not be a result of using static, rather than not multithreading properly.
Rather than accessing something globally, you should pass the dependency to where it's needed. For example, a method that uses a global variable. Pass the value to it through the parameters. This is called dependency injection.

Categories

Resources