Singleton objects and Java servlets - java

When I access a singleton Java object from withing a servlet, that object is only "single" or "one instance" for the give servlet thread or single throughout the JVM on the Server OS (like Linux)?
I mean when client connects to the servlet/service, are singleton object are unique to each thread created for each client or its unique throughout the whole JVM installed in the machine?

I think the object is unique for each user, not to the whole JVM. The only persistent information is the one you put in the user session.
I'm not sure, but I think you can acomplish to have one instance of a Class in the whole Application Server using the ClassLoader class, however I don know how it's done.
UPDATE:
Taken from the Java Article "When is a Singleton not a Singleton?"
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.

I'd say it depends on how the singleton is implemented, but all requests for a given app execute in the same VM, so it should be one instance for all requests.
EDIT: This is assuming a straight-forward Singleton implementation similar to:
public class MySingleton {
private static MySingleton _instance;
// for sake of simplicity, I've left out handling of
// synchronization/multi-threading issues...
public static MySingleton getInstance() {
if (_instance == null) _instance = new MySingleton();
return _instance;
}
}

Yes it is Singleton. But the scope of the singleton depends on where the class is located.
If it is located inside application, it is singleton for that application. If the same class is present inside another application then another object is created for that application and it is singleton for that application.
If it is located outside application and within server, it is singleton for the VM.

According to this
https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
every Web application has it's own class loader, so the singleton will be unique for one application and it can't be visible to another

When you create a Singleton instance, all request instances will share the same instance for the current class loader it uses.

Since all the Servlets run on a webserver which runs on a single JVM, there will be only a single Singelton Object for all your servlets.

Related

How java ensures only one instance of an enum per JVM

How does Java ensure internally that only one instance of an ENUM would exist per JVM? Is it created when application boots up and from that point on when multiple threads access it, it will just return the object created at startup?
Or does it implement some kind of double synchronization similar to the singleton pattern so that even if multiple threads access it, only one istance will be created?
as you can read in this answer enum instances are static class fields and so are initialized as part of class loading when you 1st access the class.
classloading is synchronized internally so that ensures enum instances are singletons (singletons within the same classloader, that is. if you have the same enum loaded by multiple loaders you will get multiple instances)
Enum instances are created at class loading time. If the same enum gets loaded by more than one classloader (when classloading games are being played by, for example, a web app container), you will have multiple incompatible instances in memory.

Singleton's other members

My question is broad, so I've split in two parts, and tried to be as specific as I can with what I know so far.
First part
A singleton holds a private static instance of itself. Some questions about singletons:
1. Should it's members also be static, or does that depend on the requirements?
2. If the answer to 1. is unequivocally yes, then what would be the point of having a private instance variable to begin with, if all members belong to the class?
3. Is the private instance needed because the JVM needs a referable object (THE singleton) to hold on to for the length of its (JVM's) life?
Second part
There is a requirement to make multiple concurrent remote calls within a tomcat hosted web application (the app utilizes GWT for some components, so I can utilize a servlet for this aforementioned requirement if a good solution requires this). Currently, I create an executor service with a cached thread pool into which I pass my callables (each callable containing an endpoint configuration), for each individual process flow that requires such calls. To me it would make sense if the thread pool was shared by multiple flows, instead of spawning pools of their own. Would a singleton holding a static thread pool be a good solution for this?
One note is that it is important to distinguish between the concept of a singleton (a class/object that has only a single instance) and the design pattern which achieves this via a class holding a single static instance of itself accessible in the global static name space. The concept of a singleton is frequently used in designs, the implementation of it via the singleton design pattern, however, is often frowned upon.
In the below, singleton is used to refer to the specific design pattern.
Part 1
A Singleton's members do not need to be static, and usually are not.
See 1.
A singleton (design pattern) requires an instance to itself in order to return that instance to users of the singleton, as well as keeping a reference to itself active to avoid garbage collection (as you suggest). Without this single instance, the object is essentially not an implementation of the singleton design pattern. You can create a class for which you only create a single instance and pass this class around where it is required (avoiding the global static namespace), and this would essentially be a recommended way to avoid using the singleton pattern.
Part 2:
Sharing your thread pools is probably wise (but depends on your requirements), and this can be done in a number of ways. One way would be to create a single pool and to pass this pool (inject it) into the classes that require it. Usual recommendation for this is to use something like Spring to handle this for you.
Using a singleton is also an option, but even if your thread pool here is encapsulated in a singleton, it is still generally preferable to inject this singleton (preferably referenced via an interface) into dependent objects (either via a setter or in their constructor) instead of having your objects refer to the singleton statically. There are various reasons for this, with testing, flexibility, and control over order of instantiation being some examples.
A Singleton's members need not be be static.
Invalidated by answer to point 1.
The instance of itself that the singleton need not be private either. You need an instance stored to a static member (public or private) if you have any other non-static member on the singleton. If there is any non-static member(it depends on your requirement) , then you need an instance to access that member(yes, JVM needs a referable object if the member is non-static)
Singleton member doesn't need to be static
Look at point 1
Singleton instance must be static (of course) and must be accessed by a static method; in addiction must have a private constructor to prevent new instance to be created
public class SingletonNumber10 {
public static SingletonNumber10 getInstance() {
if(null == instance) {
instance = new SingletonNumber10(10);
}
return instance;
}
private int number;
private static SingletonNumber10 instance;
private SingletonNumber10(int number) {
this.number = number;
}
public int getNumber() {
return this.number;
}
public static void main(String[] args) {
System.out.println(SingletonNumber10.getInstance());
System.out.println(SingletonNumber10.getInstance());
}
}
A singleton holds a private static instance of itself.
Not always, in fact, that's not even the best way to do it in Java.
public enum Director {
INSTANCE;
public int getFive() {
return 5;
}
}
Is a perfectly valid singleton, and is far more likely to remain the only copy in existence than a class that holds a private static instance of itself.
1. Should it's members also be static
No, the members should not be static, because then there is no need for a class, and therefore no need for that class to be a singleton. All static routines are subject to code maintenance issues, similar to C / C++ functions. Even though with singletons you won't have multiple instances to deal with, having the method off of an instance provides you with certain abilities to morph the code in the future.
2. If the answer to 1. is unequivocally yes.
It's not, so no need to answer #2.
3. Is the private instance needed because the JVM needs a
referable object (THE singleton) to hold on to for the
length of its (JVM's) life?
No, the private instance is needed because you have to have some ability to determine if the constructor was called previous to the access. This is typically done by checking to see if the instance variable is null. With race conditions and class loader considerations, it is incredibly difficult to make such code correct. Using the enum technique, you can ensure that there is only on instance, as the JVM internals are not subject to the same kinds of race conditions, and even if they were, only one instance is guaranteed to be presented to the program environment.
There is a requirement to make multiple concurrent remote calls within
a tomcat hosted web application (the app utilizes GWT for some components,
so I can utilize a servlet for this aforementioned requirement if a good
solution requires this). Currently, I create an executor service with a cached
thread pool into which I pass my callables (each callable containing an endpoint
configuration), for each individual process flow that requires such calls. To
me it would make sense if the thread pool was shared by multiple flows, instead
of spawning pools of their own. Would a singleton holding a static thread pool be
a good solution for this?
It depends. What are the threads in the pool going to be doing? If it's a thread to handle the task, eventually they will all get tied up with the long running tasks, possibly starving other critical processing. If you have a very large number of tasks to perform, perhaps restructuring the processing similar to the call-back patterns used in NIO might actually give you better performance (where one thread handles dispatching of call-backs for many tasks, without a pool).
Until you present a second way of handling the problem, or make more details of the operating environment available, the only solution presented is typically a good solution.
PS. Please don't expand on the details of the environment. The question submission process is easy, so if you want to expand on the second part, resubmit it as an independent question.

Multiple Stateless Beans using same static method

I came across a problem while working with stateless EJB. I want that a particular static method should be used in that EJB but this method is so important and it has static dependency.
As we know instances of stateless session beans are created as per requirements (one or many). So how can I be sure that all the EJB are using a single copy of that static method. I am not sure but I think every different class who use a static method will load different copy of class and then execute a different copy of the static method.
And I can't rely on singleton EJB as it not guaranty that only one copy will remain because if more than one JVM required by server. Different copy of singleton EJB will be in to existence in different JVM.
Thanks in advance.
Static methods are one per class, even if you create thousands of instance of that class all of them will see just one copy of your static method.
Now as per Spec you should not have static methods in your EJB, you should consider moving this as part of utility if you want it static, or else make it non static.
From the Spec:
EE.5.2.3 Annotations and Injection
As described in the following sections, a field or method of certain
container-managed component classes may be annotated to request that
an entry from the application component’s environment be injected into
the class. Any of the types of resources described in this chapter may
be injected. Injection may also be requested using entries in the
deployment descriptor corresponding to each of these resource types.
The field or method may have any access qualifier (public, private,
etc.). For all classes except application client main classes, the
fields or methods must not be static.

Static variables restriction in session beans

It's impossible to use static variables on a session bean code. Is this restriction arbitrary or fundamented? And why?
Best regards
As stated in the FAQ on EJB restrictions, one of the restrictions for using EJBs is:
enterprise beans should not read or write nonfinal static fields
Further expanded in the discussion on static fields:
Nonfinal static class fields are disallowed in EJBs because such fields make an enterprise bean difficult or impossible to distribute. Static class fields are shared among all instances of a particular class, but only within a single Java Virtual Machine (JVM). Updating a static class field implies an intent to share the field's value among all instances of the class. But if a class is running in several JVMs simultaneously, only those instances running in the same JVM as the updating instance will have access to the new value. In other words, a nonfinal static class field will behave differently if running in a single JVM, than it will running in multiple JVMs. The EJB container reserves the option of distributing enterprise beans across multiple JVMs (running on the same server, or on any of a cluster of servers). Nonfinal static class fields are disallowed because enterprise bean instances will behave differently depending on whether or not they are distributed.
It is acceptable practice to use static class fields if those fields are marked as final. Since final fields cannot be updated, instances of the enterprise bean can be distributed by the container without concern for those fields' values becoming unsynchronized.
It is fundamental. As per this sun documenation,
Nonfinal static class fields are disallowed in EJBs because such fields make an enterprise bean difficult or impossible to distribute. Static class fields are shared among all instances of a particular class, but only within a single Java Virtual Machine (JVM). *
static means unique for a class OR for all it's objects.
Now, javabeans are supposed to have user-specific data, static fields don't make any sense for these.
One user edits a variable, ant it'll be updated for all other users too. (at free of cost :-)).
However if you want static behaviour for these (i.e. using same data for all users), you have application for that purpose.

How to create a true singleton in java?

I am facing a problem with my singleton when used across multiple class loaders. E.g Singleton accessed by multiple EJBs. Is there any way to create a singleton which has only one instance across all class loader?
I am looking for pure java solution either using custom class loader or some other way.
The only way would be to make your singleton class be loaded by a single classloader - put that jar file in the bootclasspath, for example.
A static variable is inherently tied to the classloader which loaded the class containing that variable. It's just the way it works. If you need absolutely one instance, you need that class to only be loaded by one classloader.
JavaEE app servers generally solve this problem by setting up the singleton as a "service", the exact definition and configuration of which depends on the appserver in question.
For example, in JBoss you could use a xyz-service.xml descriptor to set up a singleton object that hangs off the JNDI or JMX tree, and your application components (e.g. your EJBs) would fetch the singleton from the tree. That protects you to some extent from the underlying classloader semantics.
J2EE is designed with clustering in mind, so any designs that it supports are going to have to work with multiple JVM's. I take it from your question that you aren't concerned about a clustered environment, so a simple insertion into JNDI on your app server should do it. In Glassfish, that is called a lifecycle listener. After the startup even, insert your singleton into JNDI, and then have everything else do a JNDI lookup to find it.
Note that GlassFish could still mess you up here, in that it could serialize the class to JNDI causing you to get different instances. I doubt it actually does this within one JVM, but you won't know until you try it.
The real bottom line answer is that J2EE is hostile to a global true singleton, and the J2EE way around the problem is to rethink the solution. Something like a database to hold values or some other external service that can ensure that only one instance of the data (even if multiple instances of objects representing the data) exists is the J2EE way.
To achieve TRUE Singleton, you have follow below guidelines:
Make your class as final. Others can't sub-class it and create one more instance
Make your Singleton instance as private static final
Provide private constructor and public getInstance() method.
Make sure that this Singleton class is loaded by one ClassLoader only
override readResolve() method and return same instance without creating new instance in de-Serialization process.
Sample code:
final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
Refer to below SE question for more details:
What is an efficient way to implement a singleton pattern in Java?

Categories