I'm trying to create a cache in a webservice. For this I've created a new Stateless Bean to provide this cache to other Stateless beans. This cache is simply a static ConcurrentMap where MyObject is a POJO.
The problem is that it seems as there are different cache objects. One for the client beans, and another locally.
-CacheService
-CacheServiceBean
-getMyObject()
-insertMyObject(MyObject)
-size()
-SomeOtherBean
cache = jndiLookup(CacheService)
cache.insertMyObject(x)
cache.size() -> 1
After this assignment, if I call cache.size from inside the CacheServiceBean, I get 0.
Is it even possible to share static singletons through beans? Finally I decided to use a database table, but I'm still thinking about this.
Thanks for your responses.
As far as I remember you cant be certain that the stateless bean is global enough for you to keep data in static fields. There exist several caching frameworks that would help you with this. Maybe memcache?
EDIT:
http://java.sun.com/blueprints/qanda/ejb_tier/restrictions.html#static_fields says:
Nonfinal static class fields are
disallowed in EJBs because such fields
make an enterprise bean difficult or
impossible to distribute
On the surface, this seems like a contradiction in terms, as a cache is almost certainly something I would not consider stateless, at least in the general sense.
#Stateless
public class CacheSessionBean implements CacheSessionLocal {
private static Map<String, Object> cacheMap = new HashMap<String, Object>();
public Object getCache(String key) {
return cacheMap.get(key);
}
public void putCache(String key, Object o) {
cacheMap.put(key, o);
}
}
The caveats regarding distribution of EJBs in a cluster apply to static variables. However, if you're not clustering, they pretty much don't apply to you, so statics are "okey dokey" at this level.
You WILL have synchronization issues.
One way to mitigate that is to configure your container to only create and pool a single instance of the CacheSession bean, then the container will manage that synchronization for you.
You could also manage the synchronization yourself, but you shouldn't do that at the EJB method level, rather you would likely be better having a synchronized Cache object (vs, say, a generic HashMap).
But the key take away is at this point, static variables are simply static variables.
In theory, you will need to be cognizant of the container lifecycle for your Session Bean (as it can potentially release all instances and thereby the actual bean class could be eligible for GC, thus potentially losing any static data). However, in practice, if the service is popular this is unlikely to happen. But, FYI it COULD happen.
When using stateless beans, you have no control of how many instances of them you have (that's up to your app server to take care of). You could have gotten the output from another bean than the one you looked up from your client. Did you print that in your log? In that case, you maybe should've seen more than one output. The point is that you can't know which instance you get when you look up a stateless bean via jndi (you just get one).
And, you don't have state, so I don't know if this is the best choice for a cache.
By static singleton i suppose you mean a singleton object?
Yes, it shouldn't be a problem to access a singleton through many beans. But remember the concurrency problems you'll probably get. The app server (beans in general) abstracts a lot from you.
I know this post was a while ago but there appears to be a new Singleton Bean that will meet the needs of a cache the original question was aiming at:
http://download.oracle.com/javaee/6/tutorial/doc/gipjg.html
Singleton session beans offer similar functionality to stateless session beans but differ from them in that there is only one singleton session bean per application, as opposed to a pool of stateless session beans, any of which may respond to a client request. Like stateless session beans, singleton session beans can implement web service endpoints.
I've tried creating one and referencing it wo issues from a WebService/Stateless bean. worked as advertised.
Related
I have a slight dilemma involving Guice and avoiding non-Guice singletons. Consider a multi-module project where there are 3 modules: shared, frontend and backend. Both the frontend and the backend use an instance of a Profiling class inside of the shared module (which times methods, and is used extensively throughout the project).
Almost every single class requires the use of this Profiling instance (including User objects created dynamically when a user connects).
If every single class requires an instance of the Profiling class, there are drawbacks to different methods of doing it:
Solution 1 (in the constructor, copied to the instance field):
private final Profiling profiling;
#Inject
public User(Profiling profiling, String username)
Drawback: You have to include a Profiling object in every single constructor. This is cumbersome and slightly pointless. You also have to store Guice's Injector statically (or inject it) so that you can create the User objects on-the-fly and not just when the program is first loaded.
Solution 2 (as a instance field only):
#Inject
private Profiling profiling;
public User(String username)
Drawback: Similar as above, you have to use Guice's Injector to instantiate every single object. This means that to create User objects dynamically, you need an instance of the Injector in the class creating the User objects.
Solution 3 (as a static field in one (main) class, created manually by us)
public static final Profiling PROFILING; // Can also use a get method
public Application() {
Application.PROFILING = injector.getInstance(Profiling.class)
}
Drawback: Goes against Guice's/dependency injection recommendations - creating a singleton Profiling object which is accessed statically (by Application.PROFILING.start()) defeats the purpose of Guice?
Solution 4 (as a static field in every single class, injected by Guice)
#Inject
private static Profiling profiling;
// You need to request every single class:
// requestStaticInjection(XXXX.class)
Drawback: Again, this goes against Guice's/dependency injection recommendations because it is statically injecting. I also have to request every single class that Guice needs to inject the Profiler into (which is also cumbersome).
Is there any better way to design my project and avoid falling back to the singleton design patterns I used to use?
TL;DR: I want to be able to access this Profiling instance (one per module) across every single class without falling back to singleton design patterns.
Thanks!
Pragmatically, I would use a normal singleton, maybe through a single-field Enum or a similar pattern.
To see why, you should ask the question: What is the purpose of Guice, and of dependency injection in general? The purpose is to decouple the pieces of your application so they can be independently developed and tested, and centrally configured and rearranged. With that in mind, you need to weigh the cost of coupling against the cost of decoupling. This varies based on the object you're choosing to couple or decouple.
The cost of coupling, here, is that you would be unable to operate any piece of your application without a real working instance of Profiling, including in tests, including for model objects like User. Consequently, if Profiling makes any assumptions about its environment—the availability of high-resolution system timing calls, for instance—you will be unable to use classes like User without allowing Profiling to be disabled. Furthermore, if you want your tests to profile with a new (non-Singleton) Profiling instance for the sake of test isolation, you'll need to implement that separately. However, if your Profiling class is lightweight enough not to pose a huge burden, then you might still choose this way forward.
The cost of decoupling is that it can force every object to become an injectable, as opposed to a newable. You would then be able to substitute new/dummy/fake implementations of Profiling in your classes and tests, and reconfigure to use different Profiling behavior in different containers, though that flexibility may not have immediate benefits if you don't have a reason to subsitute those implementations. For classes like User created later, you would need to pursue factory implementations, such as those provided through Guice assisted injection or AutoFactory code generation. (Remember that you can create an arbitrary number of objects by injecting Provider<T> instead of T for any object you would otherwise inject, and that injecting a Factory instance would be like customizing a Provider to take get parameters you choose.)
Regarding your solutions:
Solutions 1 and 2, per-object injection: This is where a Factory would shine. (I'd favor constructor injection, given the choice, so I'd go with solution 1 between them.) Of course, everything that creates a new User would need to instead inject a User.Factory, so that may turn a tightly-scoped project into a project to convert every class in your codebase to DI—which may be an unacceptable cost for what you're trying to do now.
// Nested interface for your Factory:
public interface Factory { User get(String username); }
// Mark fields that the user provides:
#Inject public User(Profiling profiling, #Assisted String username) { ... }
// Wire up your Factory in a Module's configure:
install(new FactoryModuleBuilder().implement(User.Factory.class));
// Now you can create new Users on the fly:
#Inject User.Factory userFactory;
User myNewUser = userFactory.get("timothy");
Solution 3, requesting static injection of a main holder approximates what I had in mind: For the objects not created through dependency injection, request static injection for a single class, like ProfilingHolder or somesuch. You could even give it no-op behavior for flexibility's sake:
public class ProfilingHolder {
// Populate with requestStaticInjection(ProfilingHolder.class).
#Inject static Profiling profilingInstance;
private ProfilingHolder() { /* static access only */ }
public static Profiling getInstance() {
if (profilingInstance == null) {
// Run without profiling in isolation and tests.
return new NoOpProfilingInstance();
}
return profilingInstance;
}
}
Of course, if you're relying on calls to VM singletons, you're really embracing a normal VM-global static singleton pattern, just with interplay to use Guice where possible. You could easily turn this pattern around and have a Guice module bind(Profiling.class).toInstance(Profiling.INSTANCE); and get the same effect (assuming Profiling can be instantiated without Guice).
Solution 4, requestStaticInjection for every single class is the only one I wouldn't consider. The list of classes is too long, and the likelihood that they'll vary Profiling is too slim. You'd turn a Module into a high-maintenance-cost grocery list rather than any sort of valuable configuration, and you'd force yourself into breaking encapsulation or using Guice for testing.
So, in summary, I'd choose Guice singleton injection for your current injectable objects, normal singleton for your current newable objects, and the option of migrating to Factories if/when any of your newables make the leap to injectables.
I have read many stackoverflow questions on this but phrased differently and not answered what I was looking for. I don't expect any code solutions but a behavioral explanation of singleton object in multi-threaded environment. Answers with some links with explanation would be great.
Question 1:
If there are multiple thread that needs to access singleton object(say configured as singleton bean in spring config), then is it that only one thread is able to get access and others are blocked till current holding thread releases it.
For me blocking here makes sense, because there is only one object and all threads cannot get same object at the same time.
So if I configure my DAO as singleton bean then if multiple users(threads) try to do reads and write through that DAO then it doesn't actually happen concurrently but sequentially ---> a performance issue in database intensive application.
On the other hand most of the DAOs are stateless(atleast in my case), so instead of configuring it as Singleton, I can instantiate it wherever I need and do the operations concurrently, but each object instantiation may take some time and memory. So it is a design decision.
In my case, since DAO has no state variable so memory would be negligible, so if my above theory is correct then I would go with 2nd option i.e. choosing concurrency over memory.
Question 2: For the question asked here
I think the best answer is below by S.Lott(I don't know how to point link
directly to the answer so copying the answer):
Singletons solve one (and only one) problem.
Resource Contention.
If you have some resource that
(1) can only have a single instance, and
(2) you need to manage that single instance,
you need a singleton.
Here my question is if above answer is true--> That would be the reason for loggers implemented as singletons because you have one log file(single resource).
You don't want that due to time slicing if one thread has written part of some log into the file and then suspended and then thread-2 writes its part and then thread-1 again, thereby making log file gibberish.
I stroke above text because I think if one thread is logging then second thread cannot log at all(blocked) because of singleton config, there by avoiding making log file a gibberish.
Is my understanding right?
"Singleton" has no meaning in the Java programming language. It's just a design pattern. The behavior of a singleton object that is shared by many threads is no different from the behavior of any other object that is shared by many threads.
It's safe if, and only if, you make it safe.
The quote you have is correct but incomplete. Singleton have more purposes, which hopefully becomes clear later on.
The answer to your first question is, it depends on the bean and how it is implemented. Instances instantiated by Spring do not guarantee thread-safety. For the purpose of answering this question, suppose that there are two possible categories of implementations: stateful and stateless. An implementation can be considered stateful if there are any methods that require external resources (e.g. field variables, database access, file access) that are mutable. On the other hand, an implementation is stateless if all the methods are able to execute their tasks using only their parameters and immutable external resources.
class Stateful {
private String s; // shared resource
void setS(String s) {
this.s = s;
}
}
class Stateless {
int print(String s) {
return s.size();
}
}
Now, if the implementation is stateless, it generally makes sense for it to be a singleton. Because a stateless class is inherently thread-safe. Multiple threads can use the methods concurrently (without blocking). Just because a class is stateless does not mean that it consumes negligible memory. In Java, instantiating a class is considered an expensive operation.
More work is required for stateful implementations to be a singleton. Again for the purpose of answering this question, suppose that there are two categories of implementation: blocking and non-blocking. Blocking is as described (although there are various types of blocking). Non-blocking means that multiple threads can call the methods concurrently. Typically, there is a thread specially for the non-blocking implementation for processing.
Loggers are good examples of non-blocking implementations. Below is a highly simplified code.
class Logger {
private List<String> msgs = new CopyOnWriteArrayList<>();
void log(String msg) {
msgs.add(msg);
}
private void process() {...} // used internally by a thread specially for Logger
}
As for question 2, the basic answer is no; singletons are not all bad. Design patterns are double-edge swords. Use them wisely and they improve your code; use them badly and they create more problems than they solve.
Whatever #james said is correct. Coming to your questions:
Question 1: Multiple threads can get access to singleton object without blocking unless you make the get method which returns the object synchronized. Please see below(Multiple threads can get a reference to singleton object without getting blocked).
public class Singleton {
private Singleton() {
}
private static class SingletonHelper {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHelper.INSTANCE;
}
}
Question 2: No your understanding is incorrect. If one thread is writing, another thread must wait, this is not because of singleton config, but because there might be a possibility that the object(file) may end up in inconsistent state; same is applicable for any object not synchronized properly.
you are linking then singleton pattern and a multithread application assuming that the access to the singleton object must be serialized; this is not true.
The requirement is that the singleton must be thread safe.
Consider the DAO example in your question; assuming the each invocation is stateless (i.e. you don't share variables within the class but only witihin the methos) you don't need multiple instance of the same DAO, in a Spring application usually there is one or more manager classes (usually you manage then DB transactions of these manager classes using AOP); each of them has a reference to a single DAO. Each time a DAO object is invoked it gets a DB connection form the data source and it executes the desired operation, then it releases the connection to the data source.
When multiple threads call your manager class you need to acquire/release the DB connection in a thread safe way. Usually Spring hides this complexity and you don't need to worry about that.
A pseudo code for the dao is something like
public void doSomeDBOperation(YourObject param) {
Connection connection=acquireDBConnection();//the connection must be acquired in a thread safe way
SQLStatement statement=connection.createStatement(yourSQL);
//do the operation with your param;
releaseDBConnection(connection);
}
Spring does sometinh similar under the hood it acquires a Db connection in the AOP aspect, it save in thread local variable so it ca be used by multiple DAOs and you can manage the transaction over the connection.
So one manager, one dao and multiple DB connections is a way to manage multithread operations in parallel (you serialize only the DBconnection lease/release assuming you are using a connection pool) and doing DB operation without blocking (at a java level on the db level things operations may lock in order to guarantee integrity constraints).
Regarding the logger question I assume you are refering to the way most logging library are used i.e you declare a static logger in each of you classes:
public class MyClass {
private static final Logger logger=LoggerFactory.get(MyClass.class.getName());
.....
}
The logger class and the file where you log are not directly linked, with Log4J, LogBack, etc you can log to multiple files with one log call, you can even log to something that is not file (a socket for example). The real writing operations are done by the appenders, the appenders must be thread safe and serialize the access to the underlying resource if needed. In you application you declare multiple loggers (one for each class) so there is one singleton per class not only one logger class in you application.
Different threads can invoke the same logger in paralled but it's the underlyng appender guarantees that the access to the underlyng file (o to something else) is serialized if needed (if you have an appender that sends a mail instead of writing a file you can do it concurrently).
If you want to combine multithreading and a single logfile that's not achieved by singletons, singletons only have influence in one thread to avoid another one from popping up.
Now if you break this by using multiple threads, singletons won't help you. If they did, the second thread would just be incapable of logging.
In many of the projects I have worked on we often have a lot of classes that map content from one domain model to another. For example from a WSDL generated model to a project specific one.
for example
public class FooBarContentMapper {
public static Foo fromWsToDomain(FooType fooType) {
...
}
}
this can also be a non-static method and the service layer can have a mapper object field instead of calling the static method:
public class FooBarContentMapper {
public Foo fromWsToDomain(FooType fooType) {
...
}
}
I find both ways used a lot, but:
is one of the solutions more efficient in any way?
are any of the solutions considered best practice?
"Is one of the solutions more efficient in any way?"
Define "efficient".
If, by "efficient", you're referring to CPU time and memory requirements, then the "instance" approach can never be more efficient than the "static" approach; at best, it can be as efficient as the static approach, and the difference depends on the frequency of object instantiation, read: how many times are you going to instantiate the "instance" approach.
"Are any of the solutions considered best practice?"
No. The "best practice" here is to match your design to your requirements.
If the mapping operation requires maintaining state, such as dependencies on other services/mappers/whatnot, then going with the "instance" approach makes more sense. One thing you don't want to get into is a world where your application's design consists of singletons that depend on each other. Use the "instance" approach, preferably using an auto-wiring facility such as the Spring Framework or CDI.
If the mapping operation requires no state, and you have an extremely high confidence in that it will never require state in the future, then use the "static" approach - unless you already have an auto-wiring facility at hand, in which case, you might as well choose the "instance" approach with auto-wiring and guarantee that, if the mapping operation requires state in the future, you won't have to alter your design much.
There are other things to consider:
Is your code testable. Mappers are used as collaborators so unit testing the object using the mapper should focus on behavior (i.e is the mapper being used when expected) ?
Is the static class used in more than one place and subject to race condition because the transform method takes a mutable object(remember, stateless static classes are still subject to race condition when taking a mutable object that is referenced by two different threads at same time)?
Does the static object actually share its life-cycle with the object using it?
If the answer is yes to any of these, you should consider switching to instance.
Hi I got this asked in an interview question paper.
Singleton and Prototype (non-singleton) which is stateful and which is stateless
I am not sure if prototype is stateless ? Is there any problem with the question ?
The question itself is poorly worded. You can have state in both Singletons and Prototypes (instances), as in it is legal code, but you do not need to have state in either cases. Since Spring is mentioned, I will try to answer this in regards to working with Spring.
In terms of Spring bean scope, singleton will cause the ApplicationContext to create a single instance and use that instance everywhere the bean is asked for. prototype will cause the ApplicationContext to create a new instance each time the bean is asked for.
It is ok for both of these to be stateful.
This question looks pretty legal (though poorly worded) if you read "stateless" as "doesn't have conversational state", i.e. a state related to a conversation with a particular client.
In these terms, singleton-scoped beans are usually stateless, because they are used by multiple clients simultaneosly and their states are not client-specific.
On the contrary, prototype-scoped beans are often created in a context of a conversation with a particular client (though request and session scopes may be more appropriate sometimes), so that their states are related to those conversations (because if your bean don't need to keep any conversational state, you can make it a singleton). In this sense prototype beans are stateful.
Prototype beans and Singleton beans can both hold state. However, according to the Spring documentation, "you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans."
A better question might be "Is Singleton thread-safe?"
It's perfectly thread-safe if the state it contains is read-only and immutable. You just have to be more careful if it's mutable. If yes, it could be in danger of becoming a bottleneck for your app. Synchronizing that shared, writable state must be done.
singleton is not data object, think about singleton as data wrapper,
point of access methods,
singleton may be destroyed but presented state stored separately and independently and will be presented after singleton recreated
(android sends greetings, destroyed singletons is notorious trap)
stateless beans: beans that are singleton and are initialized only once. The only state they have is a shared state. These beans are created while the ApplicationContext is being initialized. The SAME bean instance will be returned/injected during the lifetime of this ApplicationContext. .
stateful beans: beans that can carry state (instance variables). These are created every time an object is required.
A stateless singleton is pretty much a collection of static methods; it's no different from a static util class, and it doesn't really matter how many instances there are: 0, 1, 2 or infinity.
Therefore singletons are usually stateful.
(This is why it's nonsensical to argue that a singleton implemented in enum has serialization problem automatically taken care of. It the singleton is stateless, the argument is moot; if the singleton is stateful, the argument is broken)
in my Seam webapp there is a service returning generators for document generation. These objects are without state (no fields), just methods. Is there anything wrong if there is only one instance of each generator inside the service and each request will return the same instance? Or should I always create and return a new instance?
As long as you're sure there's no state being preserved, I don't see a reason why you'd need to re-create it every time.
It'd be similar behavior to a singleton-scoped bean in Spring
Don't know about Seam but it is something like an EJB underneath, isnt' it? In the EJB world there were stateless ejbs for exactly this case: (re)using objects without state.
So if that's possible with Seam and if those objects don't have state, make them kind of stateless beans. They can be then reused safely.
Re: static methods - that might work but depending on the design used at times you can't have static methods but need object instances, like where you want a certain creation flexibility by using factories.
If the objects have absolutely no state then there is no problem with reusing them. However if they have absolutely no state why not make all the methods static and never create one at all?
EDIT:If this class is a means to pass functionality into a method, then I agree using static methods will not work. In that case then, all else being equal, I would recommend creating a new object purely to indicate to any readers that nothing is preserved between uses. However this is a weak preference, and if there is any other reason to reuse objects, go for it.