In an article called Root Cause of Singletons writed by Miško Hevery:
Now, there is one kind of Singleton which is OK. That is a singleton where all of the reachable objects are immutable. If all objects are immutable than Singleton has no global state, as everything is constant.
A singleton always has global state, because all of the design patterns of singleton expose a global reference to the single instance.
But why immutable singleton has no global state?
Since immutable object cannot be reused and are just a use and throw object, improper usage may lead to large amount of garbage, thereby lowering the performance of application.
Singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.
A singleton must be thread-safe if used in multiple threads;
immutable objects is also thread-safe but they are inherently thread-safe.
Think of this kind of Singleton that the author describes as just a static, constant object.
The singleton pattern does not necessarily guarantee immutability. So imagine that you have a Singleton that is used by many other modules/components/objects in your code and its state changes. This could arguably lead to unexpected behavior. Object A leaves the singleton in a state A, but nothing guarantees that the singleton's state won't become B after a while.
I think this is what the author tries to outline here. Example singletons of this kind are configuration objects, or static Maps.
Related
I am using spring jdbctemplate in my application and in my query I am using row mapped as new BeanPropertyRowMapper(dto.class)
But I am getting comment from my client to make row mapped thread safe. How it can be done?
The query method looks like:
jdbcTemplate.query(qry, new Object[]("abc"),
new BeanPropertyRowMapper<dto>(dto.class))
Your code is already thread-safe. But you can improve its performance by creating a constant.
The BeanPropertyRowMapper class has mutable data. But once initialized, those data don't change so the class is thread-safe.
Exemple:
private static final BeanPropertyRowMapper<dto> DTO_ROW_MAPPER = new dto<dto>(DtoDetailEvenement.class);
...
jdbcTemplate.query(qry, new Object[]("abc"), DTO_ROW_MAPPER)
Given this code called from a DAO instance method:
jdbcTemplate.query(qry, new Object[]("abc"), new BeanPropertyRowMapper<dto>(dto.class))
(where jdbcTemplate is an instance member of the DAO injected by Spring, and the DAO is a Spring-managed bean with singleton scope) then this seems ok. BeanPropertyRowMapper is stateful and would not be threadsafe if used concurrently by multiple threads, but you're not exposing it to multiple threads, you're using it in a thread-confined manner which is safe.
Java Concurrency in Practice, section 3.3, discusses thread-confinement in general:
Accessing shared, mutable data requires using synchronization; one way to avoid this requirement is to not share. If data is only accessed from a single thread, no synchronization is needed. This technique, thread confinement, is one of the simplest ways to achieve thread safety. When an object is confined to a thread, such usage is automatically thread-safe even if the confined object itself is not [CPJ 2.3.2].
It also discusses (in 3.3.2) the particular kind of thread-confinement that you're doing:
Stack confinement is a special case of thread confinement in which an object can only be reached through local variables. Just as encapsulation can make it easier to preserve invariants, local variables can make it easier to confine objects to a thread. Local variables are intrinsically confined to the executing thread; they exist on the executing thread's stack, which is not accessible to other threads. Stack confinement (also called within-thread or thread-local usage, but not to be confused with the ThreadLocal library class) is simpler to maintain and less fragile than ad-hoc thread confinement.
The only reference to the RowMapper is on the stackframe created for that method call. No other thread (including threads calling the same method on the same DAO) can access it. Tell your client this object is already safe due to being reachable only by local variables, and refer him to the quoted passage from the JCIP book, which is an authoritative reference.
J. Bloch in his Effective Java suggests we use an enum-based singleton implementation. For instance:
public enum Application {
INSTANCE;
//methods, fields
}
This implementation is nice in the case of serialization because enums provide us with the capability of serialization by default (and we don't have to be afraid of getting two different instances while deserializing the object).
My question is how this implementation respects multhreading. How to make it thread-safe? What would we probably get if we try to access it from different threads?
The actual enum behavior of instatiating the instance doesn't have an issue with thread safety. However, you will need to make sure that the instance state itself is thread-safe.
The interactions with the fields and methods of Application are the risk--using either careful synchronization and locking, or purely concurrent data and careful verification that other inconsistencies can't happen, will be your best bet here.
Singleton ensures you only have one instance of a class per class loader.
You only have to take care about concurrency if your singleton has a mutable state. I mean if singleton persist some kind of mutable data.
In this case you should use some kind of synchronization-locking mechanishm to prevent concurrent modification of the state and/or use thread-safe data structures.
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.
I am working on a problem where I need to load a large number of inputs to a problem, and process those inputs to create a 'problem space' (i.e. build data structures allowing efficient access to the inputs, etc). Once this initialization is complete, a multi-threaded process kicks off which uses the organized/processed inputs extensively in a concurrent fashion.
For performance reasons, I don't want to lock and synchronize all the read operations in the concurrent phase. What I really want is an an immutable object, safe to access by multiple readers simultaneously.
For practical reasons (readability & maintainability) I don't want to make the InputManager a true immutable object (i.e. all fields 'final' and initialized in construction). The InputManager will have numerous data structures (lists and maps), where the objects in each have many circular references to each other. These objects are constructed as 'true' immutable objects. I don't want to have a 14 argument constructor for the InputManager, but I do need the InputManager class to provide a consistent, read-only view of the problem space once constructed.
What I'm going for is 'popsicle immutability' as discussed by Eric Lippert here.
The approach I'm taking relies on using 'package visibility' of all mutating methods, and performing all mutable actions (i.e. construction of the InputManager) within a single package. Getters all have public visibility.
Something like:
public final class InputManager { // final to prevent making mutable subclasses
InputManager() { ... } //package visibility limits who can create one
HashMap<String,InputA> lookupTable1;
...
mutatingMethodA(InputA[] inputA) { //default (package visibility)
//setting up data structures...
}
mutatingMethodB(InputB[] inputB) { //default (package visibility)
//setting up data structures...
}
public InputA getSpecificInput(String param1) {
... //access data structures
return objA; //return immutable object
}
}
The overall idea, if I haven't been clear enough, is that I'll construct the InputManager in a single thread, then pass it to multiple threads who will do concurrent work using the object. I want to enforce this 'two-phase' mutable/immutable object lifecycle as well as possible, without doing something too 'cute'. Looking for comments or feedback as to better ways to accomplish this goal, as I'm sure it's not an uncommon use case but I can't find a design pattern that supports it either.
Thanks.
Personally I'd stay with your simple and sufficient approach, but in case you're interested, there is such a thing as a mutable companion idiom. You write an inner class that has mutators, while reusing all the fields and getters from the enclosing instance.
As soon as you lose the mutable companion, the enclosing instance it leaves behind is truly immutable.
I think you can simply have separate interfaces for your two phases. One for the building part, the other for the reading part. This way, you separate your access patterns cleanly. You can see this as an instance of the interface segregation principle (pdf):
Clients should not be forced to depend upon interfaces that they do not use.
As long as the object is safely published, and the readers cannot mutate it.
"Publication" here means how the creator makes the object available to readers. For example, the creator put it in a blocking queue, and readers are polling the queue.
It depends on your publication method. I'll bet it's a safe one.
I was told that, I misunderstand effects of final. What are the effects of final keyword?
Here is short overview of what I think, I know:
Java final modifier (aka aggregation relation)
primitive variables: can be set only once. (memory and performance
gain)
objects variables: may be modified, final applies to object
reference.
fields: can be set only once.
methods: can't be overridden, hidden.
classes: can't be extended.
garbage collection: will force Java generational garbage collection
mark-sweep to double sweep.
Can's and Cant's
Can make clone fail (this is both good and bad)
Can make immutable primitives aka const
Can make blank immutable - initialized at creation aka readonly
Can make objects shallowly immutable
Can make scope / visibility immutable
Can make method invocation overhead smaller (because it does not need virtual table)
Can make method arguments used as final (even if thy are not)
Can make objects threadsafe (if object is defined as final, it wont make method arguments final)
Can make mock tests (not that you could do anything about it - you can say bugs are intended)
Can't make friends (mutable with other friends and immutable for rest)
Can't make mutable that is changed to be immutable later (but can with factory pattern like fix)
Can't make array elements immutable aka deeply immutable
Can't make new instances of object (this is both good and bad)
Can't make serialization work
There are no alternatives to final, but there is wrapper + private and enums.
Answering each of your points in turn:
primitive variables: can be set only once. (memory and performance gain)
Yes, but no memory gain, and no performance gain. (Your supposed performance gain comes from setting only once ... not from final.)
objects variables: may be modified, final applies to object reference.
Yes. (However, this description miss the point that this is entirely consistent with the way that the rest of the Java language deals with the object / reference duality. For instance, when objects are passed as parameters and returned as results.)
fields: can be set only once.
The real answer is: same as for variables.
methods: can't be overridden, hidden.
Yes. But also note that what is going on here is that the final keyword is being used in a different syntactic context to mean something different to final for an field / variable.
classes: can't be extended.
Yes. But also see note above.
garbage collection: will force Java generational garbage collection mark-sweep to double sweep.
This is nonsense. The final keyword has no relevance whatsoever to garbage collection. You might be confusing final with finalization ... they are unrelated.
But even finalizers don't force an extra sweep. What happens is that an object that needs finalization is set on one side until the main GC finishes. The GC then runs the finalize method on the object and sets its flag ... and continues. The next time the GC runs, the object is treated as a normal object:
if it is reachable it is marked and copied
if it is not reachable it is not marked.
(Your characterization - "Java generational garbage collection mark-sweep" is garbled. A garbage collector can be either "mark-sweep" OR "generational" (a subclass of "copying"). It can't be both. Java normally uses generational collection, and only falls back to mark-sweep in emergencies; i.e. when running out of space or when a low pause collector cannot keep up.)
Can make clone fail (this is both good and bad)
I don't think so.
Can make immutable primitives aka const
Yes.
Can make blank immutable - initialized at creation aka readonly
Yes ... though I've never heard the term "blank immutable" used before.
Can make objects shallowly immutable
Object mutability is about whether observable state may change. As such, declaring attributes final may or may not make the object behave as immutable. Besides the notion of "shallowly immutable" is not well defined, not least because the notion of what "shallow" is cannot be mapped without deep knowledge of the class semantics.
(To be clear, the mutability of variables / fields is a well defined concept in the context of the JLS. It is just the concept of mutability of objects that is undefined from the perspective of the JLS.)
Can make scope / visibility immutable
Terminology error. Mutability is about object state. Visibility and scope are not.
Can make method invocation overhead smaller (because it does not need virtual table)
In practice, this is irrelevant. A modern JIT compiler does this optimization for non-final methods too, if they are not overridden by any class that the application actually uses. (Clever stuff happens ...)
Can make method arguments used as final (even if thy are not)
Huh? I cannot parse this sentence.
Can make objects threadsafe
In certain situations yes.
(if object is defined as final, it wont make method arguments final)
Yes, if you mean if class is final. Objects are not final.
Can make mock tests (not that you could do anything about it - you can say bugs are intended)
Doesn't parse.
Can't make friends (mutable with other friends and immutable for rest)
Java doesn't have "friends".
Can't make mutable that is changed to be immutable later (but can with factory pattern like fix)
Yes to the first, a final field can't be switched from mutable to immutable.
It is unclear what you mean by the second part. It is true that you can use a factory (or builder) pattern to construct immutable objects. However, if you use final for the object fields at no point will the object be mutable.
Alternatively, you can implement immutable objects that use non-final fields to represent immutable state, and you can design the API so that you can "flip a switch" to make a previously mutable object immutable from now onwards. But if you take this approach, you need to be a lot more careful with synchronization ... if your objects need to be thread-safe.
Can't make array elements immutable aka deeply immutable
Yes, but your terminology is broken; see comment above about "shallow mutability".
Can't make new instances of object (this is both good and bad)
No. There's nothing stopping you making a new instance of an object with final fields or a final class or final methods.
Can't make serialization work
No. Serialization works. (Granted, deserialization of final fields using a custom readObject method presents problems ... though you can work around them using reflection hacks.)
There are no alternatives to final,
Correct.
but there is wrapper + private
Yes, modulo that (strictly speaking) an unsynchronized getter for a non-final field may be non-thread-safe ... even if it is initialized during object construction and then never changed!
and enums.
Solves a different problem. And enums can be mutable.
Final keyword is usually used to preserve immutability. To use final for classes or methods is to prevent linkages between methods from being broken. For example, suppose the implementation of some method of class X assumes that method M will behave in a certain way. Declaring X or M as final will prevent derived classes from redefining M in such a way as to cause X to behave incorrectly.