Why java.lang.Runtime is made singleton ? singleton requirement? - java

I am just trying to come up the use cases where developer may need to use Singleton class . Here they are:-
When we need to maintain the synchronization among resources. For
example in case of logging, multiple threads need to write to single
log file in sequence. Here singleton helps as synchronization is
required among different threads so that they write in single file
in sequence.
When object creation itself is costly which means it time
consuming operation . For example :- hibernate factory creation at
start up. I am not saying this is the case in every situation but
yes in some cases singleton helps here when same state needs to be
shared across application and object creation is costly.
In case of business service objects , singleton helps as it
forces us not to maintain the state of object which in turn makes
code better unit testable.
Is my understanding on the right track?
I was looking for example of singleton in jdk and came across Runtime class and thought why this singleton? As per my understanding reason should be the first one. For example we need synchronization so that two threads doesn't run GC at same instant. Is my logic correct?

Every Java application has a single instance of class Runtime that
allows the application to interface with the environment in which the
application is running.
It feels intuitive that since the environment in which the Java program is executing is one, static thing which is not going to change, Runtime is made singleton.
The number of processors, the total RAM, etc are not going to change even if you spawn more and more threads. Thus, making Runtime a singleton instance optimizes the execution of the program by avoiding having to create an object that contains the same information as 1000 other threads.
This is my understanding of it.

Singletons are evil. They're really global variables in disguise. They're particularly bad for unit tests as once the singleton is loaded by a classloader, it's behaviour is fixed so you can't mock it. Your code will be fixed to call that dependency forever.
A better approach would be to use dependency injection to inject that dependency exactly to where it's needed, or to pass down the dependency through your code to where it's needed.
Have a read of: http://c2.com/cgi/wiki?SingletonsAreEvil
Also you ask yourself why you would want to use a singleton. A singleton means one instance but it really means one instance per classloader. This may or may not be what you really desire for your solution.

Related

Is it safe to let "this" escape in the last statement of a constructor if it has happens-before guarantees?

A common advice in Java is to not to let the "this" reference escape during construction of an object and therefore not start any threads in a constructor. But I find myself writing a lot of classes that should start a thread using an executor. According to the common advice, I should write an extra start() method that submits the task to the executor.
But submitting a task to an executor gives happens-before guarantees as documented here. So would it be fine to submit the task in the last statement of the constructor? Or the more general question: is it safe to let "this" escape in the last statement of a constructor if that statement provides happens-before guarantees?
The Answer by Stefan Feuerhahn is correct.
I’ll add the suggestion that embedding an executor service within the class performing the work can be a “code smell”, an indication of weak design.
Generally we want to follow the single responsibility principle in our designs. A class should have a single purpose, and should try not to stray from that narrow specific purpose.
If, for example, a class were written to create a report, that class should know only about that report. That class should not know about when that report should be run, or how often to run the report, or what other code cares about if the report has been run.
Such scheduling of when to run the report is tied to the lifecycle of the app. For one important thing, the executor service must eventually be shut down when no longer needed or when the app is exiting. Otherwise the backing thread pool may continue indefinitely like a zombie 🧟. Your report-generating class should not know about when it is no longer needed, nor should it know about when or why the app is exiting.
Another aspect of the issue is that configuring an executor service involves knowing about the deployment scenario. How much RAM, how many CPU cores, how much other burden on that host machine, all contribute to decisions about how to set up the executor service(s). Your report-generating code should not have to change because of changes to your deployment situation.
The report-generating class should not know anything about the calling app’s lifecycle, not know anything about the executor service. The report-generating app should know nothing more than how to generate that one report. Some other place in your code, perhaps some report manager class or your app’s lifecycle orchestration code, should handle how often and when to run the report.
Yes, this is safe, because the statement providing happens-before guarantees will make sure all fields are correctly initialized visible to other threads. One caveat is that a subclass could ruin this safety so its better to make the class final. But, as Holger pointed out, even then an additional constructor delegating to the one that started the thread could harm safety.
The general advice "don't let this escape from the constructor" exists mainly because it is easier and thus less error prone to follow this rule then to keep all nuances in mind (like subclassing).

How to consider singleton in production code?

I have some java classes in which the members variables are all Autowired using Spring beans. I think that guarantees the singleton pattern. But I wonder how does the code run on a production server? Is singleton guaranteed per thread or is it guaranteed globally? How should I think about concurrency in development.
EDIT
An example:
A class the takes requests and response the number of requests it has received.
In this case we need to guarantee the global singleton of the counter, right? Say no matter how many servers we use, there should only be one counter. Is this guarantee implicitly?
Scope of classic singletons and Spring singletons
Singleton generally means singleton for the whole application running on a JVM.
That is the case for Java classic implementations where you implement it yourself (singleton double check idiom, enum idiom, initialization-on-demand holder idiom, and so for).
In these cases, the singleton is indeed created on the classloading of the singleton class, so a single time by the JVM.
Spring singletons work a little differently.
They indeed depend on the container. So, if you create multiple containers in a same JVM, you may create multiple singletons. Now it is really a corner case and besides these singleton beans are isolated between. So don't focus on it.
About concurrency
Singletons don't have any concurrency issue while these are immutable.
Of course, you can define dependencies and properties in a singleton.
But these should not change after the singleton instantiation.
Indeed if a singleton provides methods that allow to change its state, you are bound to have race conditions for distinct threads that manipulate that.
So as a hint, keep your singletons immutable or as immutable as you can.
If these cannot be completely immutable, you have to ensure that the race conditions are handled by synchronizing the methods/fields that need to.

What is a real use-case for #Stateless over #Singleton in EJB

if I understand EJB correctly, #Singleton is actually the same as Singleton in plain Java and also singleton in spring -> one instance, every call goes through the same instance concurrently.
#Stateless declares a bean, that could (but must not) have multiple instance, with the limitation that only one call can be in an instance at the same time. Right sofar?
This remains me on the servlet programming model: in theory servlet containers are allowed to make multiple copies of the servlet, in practice I haven't seen any servlet container to do so.
So assuming I do not have REALLY LIMITED resources like doors, windows or printers in my code (and if I did I could still solve it with queues and stuff), what is the REAL example, where usage of #Stateless is advantageous over usage of #Singleton.
regards
Leon
You can have multiple instances of a stateless bean to increase throughput.
On the other hand there is only one instance of a singleton. The reason for this is normally to share state in application scope, serializes access to resources etc., and this implies locking or synchronization.
So if you are not really having a singleton, then use a stateless bean.
If you have a "stateless singleton", there is no difference. But if you read "singleton", it has a special meaning by convention (= there must be a reason for using the singleton pattern).
Stateless implies that the bean is thread safe. This is because there is no code in the bean that relies on state. This means that running any of its methods will not affect future running of said methods.
An example of a stateless class would a class that does addition and subtraction. All the necessary parameters are passed into the method. Doing an addition or subtraction does not alter the way these methods work at a later call. This implies that you do not need to worry about concurrency with the class.
A singleton is usually used for a class that is very expensive to create such as a Database connection. You do not want every class creating a new Database connection every time they need to use the database so you have it instantiated once at program start up. Being a singleton does not necessarily mean that the class is thread safe (although it absolutely should be).
So Stateless means the class is threadsafe.
Singleton refers to the fact that the class is only created once. While this heavily implies that the class is (AND IT SHOULD BE) thread safe, it does not directly imply it like stateless does.

Java Concurrency: Alternative to Multi Threading (working with non thread safe environment)

I am working with a 3rd party proprietary library (no source code) which creates instances of a non thread safe component. Does this mean that I shouldn't use multiple threads to run jobs in parallel? Running each job in it's own JVM crossed my mind but is overkill.
Then I read the article here
http://cscarioni.blogspot.com/2011/09/alternatives-to-threading-in-java-stm.html
Is it recommended to follow that article's advice? What other alternatives exist out there?
Response to Martin James:
Vendor tells me that there is only one thread in which multiple instances of the component exist (Factory pattern to create the component instance) and each instance is independently controllable from it's API.
So does this mean that I can still use multiple threads while controlling each component instances running in one big thread?
No, it does not mean this.
It means that you should care about data protection yourself. One possible way is to synchronize access to that library in code that calls it (your code). Other possible way is using immutable objects (for example make private copy of non-threadsafe data structure every time you want to work with it).
Other way is to design your application that way that the code that works with certain object always run in the same thread. It does not mean that code that is working with other object (even of the same class) cannot run int other thread. So, the system is multi-threaded but no data clashes are created.
'Vendor tells me that there is only one thread in which multiple instances of the componenet exist (Factory pattern to create the component instance) and each instance is independently controllable from it's API.'
That is not exactly 100% clear. What I think it means is:
1) Creation of components is not thread-safe. Maybe they are all stored internally in a non-threadsafe container. Presumably, destruction of the components is not thread-safe either.
2) Once created, the components are 'independently controllable' - this suggests strongly that they are thread-safe.
That's my take on it so far. Maybe your vendor could confirm it, just to be sure, before you proceed any further with a design.
It all depends on what your code is actually doing with the components. For example, ArrayList is not thread safe, but Vector is thread safe. However, if you use an ArrayList inside a thread in a way that is thread safe or thread neutral, it doesn't matter. For example, you can use ArrayLists without any issue in a JavaEE container for web services because each web service call is going to be on its own thread and no one in their right mind would have web service handling threads communicating with each other. In fact, Vectors are very bad in a JavaEE container if you can avoid using them because they're synchronized on most of their methods, which means the container's threads will block until any operation is done.
As AlexR said, you can synchronize things, but the best approach is to really look at your code and figure out if the threads are actually going to be sharing data and state or going off and doing their own thing.

Prevent programmers from acquiring lock on class instance

Is it possible to write a class such that other programmers cannot acquire a lock on an instance of the class?
Lock-abuse, if there's a term like that, can be a serious killer. unfortunately, programmers torn between the disastrous forces of delivering thread-safe code and limited knowledge of concurrency, can wreak havoc by adopting the approach of locking instances even when they're invoking operations which really don't require the instance's resources to be blocked
The only way to do this is to ensure that the classes instances are not visible. For example, you could declare is as a private nested class, and make sure that the enclosing class does not leak reference instances.
Basically, if something can get hold of a reference to an instance, there is nothing to stop it from locking it.
Normally, it is sufficient to ensure that the reference to the lock object doesn't leak ... and not worry about the class visibility.
FOLLOW UP - in response to the OP's comments.
You cannot stop someone else's code from taking a lock an instance of one of your classes. But you can design your class so that this won't interfere with your classes internal synchronization. Simply arrange that your class uses a private object (even an Object instance) for synchronizing.
In the more general sense, you cannot stop application programmers from using your classes in ways that you don't like. Other examples I've heard of (here) include trying force people to override methods or provide particular constructors. Even declaring your class fields private won't stop a determined (or desperate) programmer from using reflection to get at them.
But the flip-side is that those things you are trying to prevent might actually not be stupid after all. For example, there could actually be a sound reason for an application to use your class as a lock object, notwithstanding your objection that it reduces concurrency. (And it in general it does, It is just that this may not be relevant in the particular case.)
My general feeling is that is a good idea to document the way your class is designed to be used, and design the API to encourage this. But it is unwise to try to force the issue. Ultimately it is the responsibility of the people who code against your classes to use them sensibly ... not yours.
If a class has members that require protection from concurrent access, locking should be done internally. Otherwise, you're forcing those who use it to understand the details of its implementation when they shouldn't be able to see past its interface.
When creating a new instance, also create a new thread which immediately synchronizes on the instance and goes to sleep (with Thread.sleep()). Any code trying to synchronize on the instance will just deadlock, thus the developer has to rethink his approach.
Disclaimer:
Don't vote me done because my suggestion is insane. I know it is. I am just answering the question. Do not actually do this!!!

Categories

Resources