Saturday, September 17, 2011

Java: Object Life Cycle

A java program creates many objects from different classes. Object in Java, interact by sending messages to each other.
After they are done doing processing, these objects are then garbage collected. After garbage collection process, the Operating System claims back the resources allocated to these objects which will be further used by new objects.

Below are the phases on which a Java object goes through out its life cycle:

1. Class Loading

Before creating object from a class, the class should be loaded to memory from the disk. The java class loader loads the class file to memory.

   When class is loaded?

  • when first time the object is being created.

  • any static field or method is accessed first time.


2. Static initializers

Java looks for any static initializers and initializes the static fields which are part of the class and not part of a specific instance of the class (object).

3. Object creation

Object is an instance of the class. It is created in below situations:

  • Declaration: when you declare object e.g. ClassA objA;

  • Instantiation: when new is used to allocate new object in heap memory e.g. new ClassA();

  • Initialization: new object is constructed e.g. ClassA();


4. Usage of the object

at this stage, programs could use the object either by accessing the fields or calling methods.

5. Cleanup

This is the last phase of the Java objects where they get recycled and the memory is claimed by the OS.
what happens on destruction?

  • Object is removed from the memory.

  • Java drops its internal references to this object.

  • Garbage Collection (GC) , runs which frees objects which are not needed any more i.e. there are no references to this object.

  • Finalization: GC gives objects a last chance opportunity to cleanup any other resources by calling its finalize() method.


 when it happens?


  • when object goes out of the scope. i.e. {...objA...}, here } becomes scope. at this time, Java run time checks for the references and lets GC recycle this object.

  • when number of references to this object in java run time memory becomes zero (0).

  • when object is explicitly set to null i.e. objA = null;, GC is called

  • finalize() method is explicitly called.

Wednesday, September 7, 2011

Difference between Java Vector and ArrayList

The Vector is an analog to the ArrayList. So, from an API perspective, the two classes are very similar.  They both use java Array internally to store the elements. There are still some major differences between these two classes and we will be going through them now...

Synchronization:

Vectors are synchronized. This means that all of its methods are thread safe.

ArrayList on the other hand, is unsynchronized, making them, therefore, not thread safe.

Using synchronization will incur a performance hit. What it means is that all the threads accessing the same Vector object are blocked until the first thread completes its operation on the object. Due to this no two threads are using the object at the same time. Hence this enforces the data consistency.

Tips: use the Vector only where it is really necessary.

Capacity and Data growth:

As we discussed above, Vector and ArrayList both hold their data in Java Array object. However when size of the Array goes beyond its allocated space, there needs to be resizing to accommodate the new elements in the Array. The expansion of the Array object is done differently for Vector and ArrayList:

Vector defaults to doubling the size of its array.

ArrayList increases its array size by 50 percent.

Tips: There is a cost involved in adding new elements to these containers. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later.
It is advisable to initialize the capacity of these containers at the time of object creation.

e.g. Vector v = new Vector(initialCapacity);

Depending on the application, choose right value for initialCapacity.

Usage patterns


These containers perform Add/Remove/Get in constant time i.e. O(1) when Add/Remove is done either at the start or end of the list. However the cost increases when Add/Remove is done inside the list. Because in this case, the iterator has to identify the position in linear time i.e. O(n).

Tips: use plain old Array in place of these containers for the performance critical applications.

Speed

ArrayList is faster than Vector. Since Vector is synchronized it pays price of synchronization which makes it little slow.

Default Size

ArrayList in Java has no default size but Vector in Java has default size of 10.

 

that's all folks!!!

Saturday, August 27, 2011

Lokpal vs Jan Lokpal Indian anti-corruption bill

Dedicated to Sri Anna Hazare ji

[caption id="attachment_63" align="alignleft" width="150" caption=""I Am Anna Hazare""]"I Am Anna Hazare"[/caption]

According to Wikipedia:

The Jan Lokpal Bill, also referred to as the citizens' ombudsman bill is a proposed independent anti-corruption law in India. Anti-corruption social activists proposed it as a more effective improvement to the original Lokpal bill, which is currently being proposed by the Government of India.

The Jan Lokpal Bill aims to effectively deter corruption, redress grievances of citizens, and protect whistle-blowers(a person who tells the public or someone in authority about dishonest or illegal activities occurring in a government department, public or a private organization or a company). If made into law, the bill would create an independent ombudsman body similar to the Election Commission of India called the Lokpal (Sanskritprotector of the people). It would be empowered to register and investigate complaints of corruption against politicians and bureaucrats without prior government approval. First passed the Lok Sabha in 1968, the bill has failed to pass the Rajya Sabha and become law for over four decades.

In 2011, civil activist Anna Hazare started a Satyagraha movement by commencing an indefinite fast in New Delhi to demand the passing of the bill. The movement attracted attention in the media, and hundreds of thousands of supporters, in part due to the organizational skills of Arvind Kejriwal. Following Hazare's four day hunger strike, Indian Prime MinisterManmohan Singh stated that the bill would be re-introduced in the 2011 monsoon session of the Parliament.Accordingly, a committee of five Cabinet Ministers and five social activists attempted to draft a compromise bill merging the two versions but failed. The Indian government went on to propose its own version in the parliament, which the activists reject on the grounds of not being sufficiently effective and called it a "toothless bill".

Anna Hazare has fought for the Jan Lokpal against the Indian government's LokPal bill. Lets see how these two bills differ:

1.

Jan Lokpal- Lokpal would have power to investigate allegations of corruption against judiciary.

Lokpal- Judiciary kept out of Lokpal's purview.

2.

Jan Lokpal- Lokpal can investigate allegations that any MP had taken a bribe to vote or speak in Parliament.

Lokpal- Excluded from the purview of Lokpal.

3.

Jan Lokpal- Lokpal should have powers to investigate allegations of corruption against the PM.

Lokpal- PM out of the purview of Lokpal while in office. Once he demits office, Lokpal can investigate complaints.

4.

Jan Lokpal- If the work of a citizen is not done by a government officer in the prescribed time, it should be deemed a violation of the citizen's charter, and as amounting to corruption. The officer should be penalised.

Lokpal- No penalties proposed.

5.

Jan Lokpal- Anti-corruption branch of CBI to be merged into Lokpal.

Lokpal- CBI untouched. Officers will be deputed to Lokpal.

6.

Jan Lokpal- The bill should create Lokayuktas at the state level.

Lokpal- The bill only creates Lokpal at the Centre.

7.

Jan Lokpal- Lokpal required to provide protection to whistleblowers, witnesses and victims of corruption.

Lokpal- Whistleblower protection part of separate law to be introduced.

 

Anna Hazare has followed Mahatma Gandhi's non-violence way to protest for bringing Jan LokPal and fasted for 12 days. Today he and his supporters across the country won the most awaited Jan LokPal bill.

Congratulations to all who were involved directly or indirectly in supporting Anna Hazare on his protest.

read more about Anna Hazare at http://en.wikipedia.org/wiki/Anna_Hazare

 

Tuesday, August 16, 2011

overview of "Gang of Four" Patterns

The design patterns are categories in three below groups:

1. Behavioral Patterns

  1. Chain of Resp. : A way of passing a request between a chain of objects. Avoid coupling the sender of a request to its receiver by giving more than one object a  chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

  2. Command: Encapsulate a command request as an object. Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

  3. Interpreter: A way to include language elements in a program. Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

  4. Iterator: Sequentially access the elements of a collection. Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

  5. Mediator: Defines simplified communication between classes. Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

  6. Memento: Capture and restore an object's internal state. Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.

  7. Observer: A way of notifying change to a number of classes. Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

  8. State: Alter an object's behavior when its state changes. Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

  9. Strategy: Encapsulates an algorithm inside a class. Define a family of algorithms, encapsulate each one, and make them interchangeable.            Strategy lets the algorithm vary independently from clients that use it.

  10. Template: Defer the exact steps of an algorithm to a subclass. Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

  11. Visitor: Defines a new operation to a class without change. Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.


2. Creational Patterns

  1. Abstract Factory: Creates an instance of several families of classes. Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

  2. Builder: Separates object construction from its representation. Separate the construction of a complex object from its representation so that the same construction processes can create different representations.

  3. Factory Method: Creates an instance of several derived classes. Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

  4. Prototype: A fully initialized instance to be copied or cloned. Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

  5. Singleton: A class of which only a single instance can exist. Ensure a class only has one instance, and provide a global point of access to it.


3. Structural Patterns

  1. Adapter: Match interfaces of different classes.Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

  2. Bridge: Separates an object’s interface from its implementation. Decouple an abstraction from its implementation so that the two can vary independently.

  3. Composite: A tree structure of simple and composite objects. Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

  4. Decorator: Add responsibilities to objects dynamically.  Attach additional responsibilities to an object dynamically. Decorators provide a             flexible alternative to subclassing for extending functionality.

  5. Facade: A single class that represents an entire subsystem. Provide a unified interface to a set of interfaces in a system. Facade defines a higher-level interface that makes the subsystem easier to use.

  6. Flyweight: A fine-grained instance used for efficient sharing. Use sharing to support large numbers of fine-grained objects efficiently. A flyweight is a shared object that can be used in multiple contexts simultaneously. The flyweight acts as an independent object in each context — it’s indistinguishable from an instance of the object that’s not shared.

  7. Proxy: An object representing another object. Provide a surrogate or placeholder for another object to control access to it.





The detailed information are at: http://www.dofactory.com/Patterns/Patterns.aspx

 

Wednesday, March 23, 2011

What is absolute value of Integer.MIN_VALUE ?

what does below code return?

[java]
int ret = Math.abs(Integer.MIN_VALUE);
[/java]

In the number system, there are more negative numbers than positive ones. Not all -ve numbers have their positive counterparts (e.g. -3 & +3). Ignoring 0. The minimum possible number in 32 bit number is 10000000000000000000000000000000(31 zeroes, say 1000...0).

Here is how absolute value is calculated.

we take Two's compliment by inverting the whole number (replace 1 with 0 and 0 with 1) and then add 1 to the final value.

Lets do it together:
in 2*32 bit number... 1000...0 is -ve

1) 2s compliment would be:

~100000...0 = 011111...1

2) add 1, would become 01111...11 + 1 = 1000000...0

so its back to the same number Integer.MIN_VALUE

Absolute value of MIN_VALUE is itself.

[java]
Integer.MIN_VALUE = Math.abs(Integer.MIN_VALUE)
[/java]

Note: Math.abs(...) doesn't guarantee to always return positive number. The same is true for "%" operator as it gives remainder but not modulo. Remainder could be negative.

Sunday, March 13, 2011

CPP Header Files

The standard practice is to have one header file (.h) per class file (.cpp). The correct use of the header files could enhance the readability and also boost the performance of the code. When deciding which portion of code to put where , think about the Locality of Reference first because this matters as well.

Below are the few points to remember while designing the header files:

1. Header file guard

All header files should be guarded well to avoid multiple inclusions in the code. e.g.

[cpp]

#ifndef MY_SAMPLE_HEADER_H

#define MY_SAMPLE_HEADER_H

//contents of the header file here...

#endif

[/cpp]

2. Header file depedencies

Any file including the header files needed to be recompiled whenever the contents in the header file changes. This leads to big dependency in the compile time. In the scenarios where including header file is not needed, forward declaring the class should be more than enough. Doing this will help not recompile the class however the symbol will be resolved at the linking phase of the compilation process.

3. Inline methods

Inline methods are defined in side the class declaration body itself i.e. in .h file instead of the .cpp file. Inlining methods which are about 10 lines big lead to better program performance.

4. Method parameter and Include file ordering

The general convention to order the parameters in the methods are input first and then output parameters. Remember that all inputs should be declared "const <data type> &_data" so that method can't modify the _data.
The output parameters are generally declared non-constant "<data_type> &_data".

The order of the header file included should be done in the order of their path names. This doesn't made any difference in the performance of the program however it improves the readability of the code.

5. Header comment

Header comments give the glimpse of what is file about and how the code has evolved since its first version.

a sample of the comment is here:

[cpp]
/* ---------------------------------------------------------------------------
**
** <filename>.h
** Description:<very brief file description>
**
** Author: <original author>
** Change History
** 1.0 - changed the accessors to inline
** -------------------------------------------------------------------------*/
[/cpp]