Wednesday, November 12, 2014

Java 8 : Not a Paradigm Shift. Just Revisiting the Old Roots 1

When I started my Bachelor's in Software Engineering back in 2007 during very early stages I was attending a Module for Programming Principles and there the lecturer said that our programs must never use global variables (Module was using C++) and each problem should be broken into a Function/Method essentially the practice Functional Decomposition. But during this time I was working as a Java Developer for a Company and my inner Java Developer opposed to this.


As Java being an Object Oriented Programming language, we are advised to think in terms of Objects rather than Function/Method. Practically functions/methods are second class citizens in Java. There is no way a Function/Method can exist without it being attached to a Class or being part of an Object. So I thought Functional Decomposition is old school and was only applicable for languages that is highly function oriented like C/C++.

But couple of years back I started reading the book Java Concurrency in Practice book and it stated that thread safety is all about protecting shared mutable state. If a Class in Java has no instance or static variables that Class becomes thread safe. One theory I learned from that book is that,

"If there are shared mutable states in a Class and if more than one thread reads those states and also if at least one thread modifies those states then access (read/modification) to those states must be synchronized"

So it all came back to me, What I learnt in 2007 as part of my Bachelor's is actually part of Java also. Global variables can be considered as shared mutable states. It is better if a Class has lesser no of shared mutable states so that in can become more concurrent friendly. Because synchronization is costly, be it Monitor lock, Copy-On-Write, Compare-And-Swap, etc. all must be used to a minimum level with shared mutable variables or the program performance can degrade.

Best approach is Immutability in classes. Immutable classes are inherently thread safe and performance degrading is not a concern. For example Java String class immutable being that after instantiate and initialization its state can not be modified. Invoking almost every Method on a String object will produce a new String object.

Furthermore the theory I learned in 2007 is so much alive today. Functional Decomposition is actually the ideal solution for today's problems. Problems broken down into Functions/Methods are easier to code/test/debug/maintain.

Next we'll see how Java 8 Helps to achieve Immutability and Functional Decomposition.

References

  1. Java Concurrency in Practice - http://jcip.net/

No comments:

Post a Comment