vinayknl.61
BAN USERSynchronization on static methods will acquire lock on Class object of the enclosing class. This means only one thread can call static synchronized methods regardless of number of instances of that class.
- vinayknl.61 March 26, 2013With immutable objects, we can avoid circular references and make GC's life easier.
I found the answer from Brian Goetz's article.
In most cases, when a holder object is updated to reference a different object, the new referent is a young object. If we update a MutableHolder by calling setValue(), we have created a situation where an older object references a younger one. On the other hand, by creating a new ImmutableHolder object instead, a younger object is referencing an older one. The latter situation, where most objects point to older objects, is much more gentle on a generational garbage collector. If a MutableHolder that lives in the old generation is mutated, all the objects on the card that contain the MutableHolder must be scanned for old-to-young references at the next minor collection. The use of mutable references for long-lived container objects increases the work done to track old-to-young references at collection time.
This can be done through the readResolve method. When an object is read, replace it with the singleton instance. This ensures that nobody can create another instance by serializing and deserializing the singleton. For Example:
public final class MySingleton {
private MySingleton() { }
private static final MySingleton INSTANCE = new MySingleton();
public static MySingleton getInstance() { return INSTANCE; }
private Object readResolve() throws ObjectStreamException {
// instead of the object we're on,
// return the class variable INSTANCE
return INSTANCE;
}
}
This will ensure that only one instance is read when we are dealing with serialization/de-serialization.
- vinayknl.61 February 20, 2013An object is considered immutable if its state cannot change after it is constructed.
Advantages :
1. Simple and Reliable Code.
2. Useful in concurrent Applications since they cannot change state, they cannot be corrupted by thread interference or present in inconsistent state.
3. Decreased overhead in Garbage Collection.
4. Reduction in code needed to protect objects in concurrent applications.
JDK Examples : String, Integer
public class Mydate {
private final Date date; // Declare the variable as final
public Mydate(Date date) {
this.date = new Date(date.getTime());
}
public getDate() {
return new Date(date.getTime()); // Need to return a copy instead of original object
}
// Note: No Setter method for date
}
make class final, fields as private final and dont provide setters for field and use only constructors to create objects.
if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller
A Java sample code
- vinayknl.61 November 15, 2013