Using Singleton enum in Spring MVC - spring

Here is my singlton class using enum:
public enum MyInstanceFactory {
INSTANCE;
private SOMEOBJECT;
private int countInitialization = 0;
private MyInstanceFactory(){
countInitialization++;
System.out.println("WOW!! This has been initialized: ["+countInitialization+"] times");
SOMEOBJECT = SOMETHING
}
public Session getSomeobject(){ return SOMEOBJECT; }
}
Now I am calling it like inside MVC controller
Session cqlSession = MyInstanceFactory.INSTANCE.getSomeobject();
In this way it calls constructer only first time and next and onwards it return the correct value for SOMEOBJECT.
My question is I want to do the same thing when a spring application start i.e. initializing contructor once and use **getSomeobject** multiple times.
I saw THIS SO ANSWER but here they are saying
If it finds a constructor with the right arguments, regardless of visibility, it will use reflection to set its constructor to be accessible.
Will reflection create problem for a singlton class?

If you need a non-subvertible singleton class (not just a singleton bean that's shared by many other beans, but actually a singleton class where the class can only ever be instantiated once), then the enum approach is a good one. Spring won't try to instantiate the enum itself, because that really makes no sense; that would be a much more extremely broken thing to do than merely calling a private constructor.
In that case, to refer to the enum instance from Spring configuration, you do the same thing as for any other static constant; for example:
<util:constant static-field="MyInstanceFactory.INSTANCE" />

Related

Spring return dynamic instance based of String value

Java Spring question:
I have a interface MyInterface with one method
void exec (String str);
I have many implementation of MyInterface, say Oneimpl, anotherimpl yetanotherimpl...and so on and can keep adding new implementations.
how do I obtain an instance of a specific implementation using just the name of the implementing class passed as a STRING value , say "someRandomImpl"
The code should be dynamic and can provide a instance of new implementations without code change.
implements ApplicationContextAware
it will autowired ApplicationContext object
use the object like
context.getBean(beanName)
then you get the bean

Why is the Java 8 Optional class final? [duplicate]

I was playing with the following question: Using Java 8's Optional with Stream::flatMap and wanted to add a method to a custom Optional<T> and then check if it worked.
More precise, I wanted to add a stream() to my CustomOptional<T> that returns an empty stream if no value is present, or a stream with a single element if it is present.
However, I came to the conclusion that Optional<T> is declared as final.
Why is this so? There are loads of classes that are not declared as final, and I personally do not see a reason here to declare Optional<T> final.
As a second question, why can not all methods be final, if the worry is that they would be overridden, and leave the class non-final?
According to this page of the Java SE 8 API docs, Optional<T> is a value based class. According to this page of the API docs, value-based classes have to be immutable.
Declaring all the methods in Optional<T> as final will prevent the methods from being overridden, but that will not prevent an extending class from adding fields and methods. Extending the class and adding a field together with a method that changes the value of that field would make that subclass mutable and hence would allow the creation of a mutable Optional<T>. The following is an example of such a subclass that could be created if Optional<T> would not be declared final.
//Example created by #assylias
public class Sub<T> extends Optional<T> {
private T t;
public void set(T t) {
this.t = t;
}
}
Declaring Optional<T> final prevents the creation of subclasses like the one above and hence guarantees Optional<T> to be always immutable.
As others have stated Optional is a value based class and since it is a value based class it should be immutable which needs it to be final.
But we missed the point for this. One of the main reason why value based classes are immutable is to guarantee thread safety. Making it immutable makes it thread safe. Take for eg String or primitive wrappers like Integer or Float. They are declared final for similar reasons.
Probably, the reason is the same as why String is final; that is, so that all users of the Optional class can be assured that the methods on the instance they receive keep to their contract of always returning the same value.
Though we could not extend the Optional class, we could create our own wrapper class.
public final class Opt {
private Opt() {
}
public static final <T> Stream<T> filledOrEmpty(T t) {
return Optional.ofNullable(t).isPresent() ? Stream.of(t) : Stream.empty();
}
}
Hope it might helps you. Glad to see the reaction!

Initiate and shutdown a instance in Spring Mvc

I have following code
public enum MyInstances {
INSTANCE;
private InstanceClass instance;
private MyInstances(String param){initTitanGraph(param);}
private void initTitanGraph(String param){
instance = SomeFactoryClass.open(param);
}
public InstanceClass getInstance(){
return instance;
}
public void destroyInstance(){
//destroy or close all instances of InstanceClass class
}
}
Now I want to call
MyInstances.INSTANCE.getInstance();
to get the instance.
and
MyInstances.INSTANCE.destroyInstance();
to destroy instance.
I am using spring mvc. How can I implement the same class using spring mvc injection such that on application shutdown destroyInstance should be called and I can also use getinstance() to get instance anywhere.
there is no destroy method unless you define it. This doesn't do anything. The actual INSTANCE is still in memory whatever you do, as a singleton.
You are applying th esingleton pattern, just about, to an Enum.
Enums are hardwired by jvm to be singletons, without any extras from the programmer.
Application start and stop in spring can be achieved with #Postconstruct and #Predestory annotations.

ejb references passed in helper class or create ejb instead

I was wondering which one of the two solutions hereunder is the best practice?
Problem : I have a stateless session bean VehicleBean, I implemented a method with business logic and persistence of a Car with its wheels , their tires, etc.
#Stateless
class VehicleBean{
#PersistenceContext
private EntityManager em;
#EJB
Inspector inspectorBean;
#EJB
DocumentBean documentBean;
public void persistCar(){
Car car = new Car();
car.setMake("Ford");
em.persist(car);
documentBean.persistDocument(new Document(car));
for (int i = 0; i < 4; i++){
createWheel(car);
}
private void createWheel(Car car){
// some business logic
inspectorBean.inspect();
Wheel wheel = new Wheel();
wheel.setCar(car);
em.persist(wheel);
...
}
...
}
I have different private methods that are called after each other (1) create car, 2) create wheels, etc) and I would like to regroup all these methods in one helper class.
Solutions:
1) Make use of a helper class CarBuilder which contains all the private methods from my VehicleBean. As I can't use ejb injection, I want to pass it by reference to the constructor as following :
public void persistCar(){
new CarBuilder(this, document, inspectorBean);
}
class CarBuilder{
private VehiculeBean vehiculeBean;
...
CarBuilder(VehiculeBean,....){
this.vehiculeBean = vehiculeBean;
}
}
2) create CarBuilder as a stateless session bean and inject the bean in the VehiculeBean.
Do you see any advantage using the 2)? So having a lot of different beans like CarBuilder, MotorcyleBuilder, etc managed by the container.
Passing references to container managed objects in constructors will decrease readability of the code (IMO). Code becomes a lot clearer if you create container managed resources with dependency injection.
Let the helper classes work with the entities instead and create a new EJB when you want to break out bussiness logic in another class.

Annotations for Java enum singleton

As Bloch states in Item 3 ("Enforce the singleton property with a private constructor or an enum type") of Effective Java 2nd Edition, a single-element enum type is the best way to implement a singleton. Unfortunately the old private constructor pattern is still very widespread and entrenched, to the point that many developers don't understand what I'm doing when I create enum singletons.
A simple // Enum Singleton comment above the class declaration helps, but it still leaves open the possibility that another programmer could come along later and add a second constant to the enum, breaking the singleton property. For all the problems that the private constructor approach has, in my opinion it is somewhat more self-documenting than an enum singleton.
I think what I need is an annotation which both states that the enum type is a singleton and ensures at compile-time that only one constant is ever added to the enum. Something like this:
#EnumSingleton // Annotation complains if > 1 enum element on EnumSingleton
public enum EnumSingleton {
INSTANCE;
}
Has anyone run across such an annotation for standard Java in public libraries anywhere? Or is what I'm asking for impossible under Java's current annotation system?
UPDATE
One workaround I'm using, at least until I decide to actually bother with rolling my own annotations, is to put #SuppressWarnings("UnusedDeclaration") directly in front of the INSTANCE field. It does a decent job of making the code look distinct from a straightforward enum type.
You can use something like this -
public class SingletonClass {
private SingletonClass() {
// block external instantiation
}
public static enum SingletonFactory {
INSTANCE {
public SingletonClass getInstance() {
return instance;
}
};
private static SingletonClass instance = new SingletonClass();
private SingletonFactory() {
}
public abstract SingletonClass getInstance();
}
}
And you can access in some other class as -
SingletonClass.SingletonFactory.INSTANCE.getInstance();
I'm not aware of such an annotation in public java libraries, but you can define yourself such a compile time annotation to be used for your projects. Of course, you need to write an annotation processor for it and invoke somehow APT (with ant or maven) to check your #EnumSingleton annoted enums at compile time for the intended structure.
Here is a resource on how to write and use compile time annotations.

Resources