effective java - creating and destroying objects
TRANSCRIPT
Creating & Destroying Objects
Reference: Effective Java - Joshua Bloch-Rohit Vaidya
Agenda
Discuss over object creation and destruction
Study best practices
Use profiler to go over how good or bad code is
Items
Item1 Consider Static factory methods
Item2 Consider builders
Item3 Enforce Singleton,private constructors or enum type
Item4 Enforce non-instanstiability private constructors
Item5 Avoid creating unnecessary Objects
Item6 Avoid finalizers
Creating Objects
When and how to create Objects
How to avoid creating them
Ensure they are destroyed
Cleanup before destruction
Item 1
Consider static factory methods instead of constructors
Item 1 Premise
Create an object
Implicitly not create objects when unnecessary
Ability to create a object of subtype
Item1 - Solution
Provide static factory methods
AdvantagesUnlike constructors they have names
Not required each time you create a new objectE.g: Boolean.valueof(boolean) never creates a object
Can return a object of any subtype of return type
DisadvantagesClasses without public or protected members cannot be sub classedThis has a hidden advantage
Not easily distinguishable from other static factory methods
Item 2
Consider builder when faced with many constructor parameter
Item 2 Premise
Many parameter constructors or static factories do not scale Hell for the client
Telescoping constructor patternWhy its bad? Hard to read/write code
Java Beans patternInconsistent path way through its construction
Does not allow your class to be immutable. Setters!!!
Item 2 Solution
Builders!!!Makes your class immutable. Important
Makes it easy to read and write code
Builders allows you to set invariants. If Invariant is not satisfied throw IllegalArgumentException
Builders can have multiple varargs where as constructor only one
The Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters"
Item 3
Enforce the singleton property with a private constructor or an enum Type
Item 3 - Premise
Make a class singleton
Avoid reflection attacks on singleton classes made singleton conventionallyAccessibleObject.setAccessible
Serialization making multiple copies of the same object
Item3-Solution
Have a public static final field which contains the instanceClass declaration makes it evident, its singleton
Have a private static field with the factory method returning the instanceThe factory API can be easily modified to make it non singleton
Use enum to create singletons
Have the constructor throw an exception to solve Reflection problem
Make all the field transient and implement a resolveObject API to resolve serialization problem
Item 4
Enforce non-instantiability with a private constructor
Item 4 Premise
Want to write a class which is a group of static methods
Write group of methods on primitive values or arrays. e.g: java.util.Arrays java.lang.Math
Don't create an object where its non-sensical to do so Utility Classes
Item 4 - Solution
Simple: Add a private constructor.
If you don't? - A default constructor gets generated. You can still do a X obj = new X(); //This is bad.
You have instantiated a class when not required
Positive Side Effect: Can't be subclasses
Item 5
Avoid creating unnecessary Objects
Premise
Reuse objects
Consequently avoid creating new instances
Reuse immutable objects and mutable objects
Avoid accidentally creating objects
Solution
String pool of-course!!!String s = new String(string);//Code smell
Use static factory methods for object creationBoolean(String) //Code smell
Reuse Mutable Objects. Assuming these objects are not expected to be mutated
Safe to reuse immutable objects
Beware of auto-boxing
Item 5 - Snippets
Item5 - Profiling
Item5 - Profiling
Item 5 Fix it
Item 5 After Fix
Item 5 After fix
Item 6
Eliminate Obsolete References
Premise
Need to understand Memory Leaks first
Don't misunderstand Java Garbage collector cleans it allObsolete References to blame.
References that will never be referenced again
Memory Leaks in caches
Listeners and their callbacks, another culpritAPI exposes where client register a call back but no mechanism to de-register them.
Solution
Nullify obsolete references
Don't make it a norm and use judiciously. Best way to let variable fall out of scope
Cache WeakHashMap Enteries will be removes automatically after they become obsolete
Store only weak references to callbacks
Avoid finalizers
Unpredictable, dangerous and unnecessary
Implementation of finalizers is JVM implementation dependent
When finalizer will be invoked is a function of the VM's garbage collection algorithm
System.gc does not guarantee finalizers execute
Performance penalty with finalizers
Don't rely on finalizer to ensure program correctness. Your design is flawed
InsteadMake use of explicit termination methods. try catch finally.
Thank you