Tuesday, April 28, 2015

ArrayList vs Vector

Similarities
  1. Both allows null and duplicates and index based and backed up by an array internally.
  2. Both are derived from AbstractList and implements List interface.
  3. Both can be iterated with Iterator or ListIterator.
       Get the Enumeration object:
     - Enumeration e = Collections.enumeration(arrayList);
    - Vector can return enumeration of items it hold by calling elements () method.
  4. Both are fail-fast.
    The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

Differences
  1. Vector is synchronized but ArrayList is not.
  2. Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field while you can increase size of ArrayList by calling ensureCapacity () method.
  3. Vector standard initial size is 10,standard  capacityIncrement is zero
    The size of the new data array will be the old size plus capacityIncrement, unless the value of capacityIncrement is less than or equal to zero, in which case the new capacity will be twice the old capacity; but if this new size is still smaller than minCapacity, then the new capacity will be minCapacity.
  4. ArrayList starts with a default initial capacity of 10,
  5. Java 1.7  ==>  int newCapacity = oldCapacity + (oldCapacity >> 1)
    Java 6 ====>    int newCapacity = (oldCapacity * 3)/2 + 1;
  6. Vector provides a method to get the current capacity but ArrayList doesn't ).
It would be wrong to write a program that depended on this exception for its correctness, the fail-fast behavior of iterators should be used only to detect bugs.

If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html

Set Collection


The "java.util.Set" interface is a subtype of the "java.util.Collection" interface that:
  1. Can not contain duplicates.
  2. Allow one null element.
  • Set Implementations:
  1. java.util.EnumSet
  2. java.util.HashSet
  3. java.util.LinkedHashSet
  4. java.util.TreeSet
  5. java.util.SortedSet

HashSet is unordered collection (Doesn't maintains insertion order) , It changes the order of the  inserted elements.

LinkedHashSet guarantees that the order of the elements during iteration is the same as the order they were inserted.

TreeSet guarantees that the order of the elements when iterated is the sorting order of the elements.

  • Operations:
  1. To add elements to a Set you call its add() method.
  2. You remove elements by calling the remove(Object o) method.
Remove Duplicates from a Collection:
Suppose you have a Collection, c, and you want to create another Collection containing the same elements but with all duplicates eliminated:

Collection<Type> noDups = new HashSet<Type>(c); 

In jdk 8 you can remove duplicate using Lambdas:
c.stream().collect(Collectors.toSet()); // no duplicates

  • Iterate Elements:
//access via Iterator
Iterator iterator = setA.iterator();
while(iterator.hasNext(){
  String element = (String) iterator.next();
}


//access via new for-loop
for(Object object : setA) {
    String element = (String) object;
}
https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
http://fastlearned.blogspot.com/2012/08/java-collection.html

Map


Collection


Wednesday, April 22, 2015

Stack and Heap memory in java basic knowledge Video

String, Stringbuffer and StringBuilder in java basic knowledge Video

We should always use StringBuilder append() method rather than String "+" operator to avoid cost. 

Note that what "+" operator does is:
  1. create a new string;
  2. make a copy of the left string;
  3. append the right char/string to the end.

So, a series of "+" operation is O(n^2)-time, not O(n).
StringBuilder is smarter and you can think it as a dynamically resizing array of char.
No copies for append() and it can output a String by calling toString() method.

Note: StringBuilder has no synchronization, i.e. it is not thread-safe.
If synchronization is required, it is recommend to use StringBuffer.

http://sophie-notes.blogspot.com/2013/02/java-stringbuilder-vs-string.html

JVM HotSpot memory

The JVM HotSpot memory is split between 3 memory spaces
  • The Java Heap.
  • The PermGen(perm) (permanent generation).
  • The Native Heap (C-Heap).

The Java Heap
  • Stores java objects.
  • Applicable for all JVM vendors.
  • It's usually  divided into generations:a-  The young generation (nursery):Stores short-lived objects that are created and immediately garbage collected.b-  The old generation (tenured):Objects that persist longer are moved to the old generation.
  • Start-up arguments and tuning:
    -Xmx (maximum Heap space) -Xms (minimum Heap size)
PermGen 
  • Keep information for the loaded classes (storing the Java Classes metadata)
  • String Pool which created by String.intern() method.
  • The PermGen space is only applicable to the HotSpot VM.
  • In Java 8, Oracle replaced the PermGen space for the HotSpot VM  with Metaspace.
  • Start-up arguments and tuning
    -XX:MaxPermSize (maximum size)    -XX:PermSize(minimum size)
Native Heap
  • Store third party native code objects.
  • Applicable for all JVM vendors.
Eating memory cases 
  • The more class loaders and classes that you load at runtime, higher demand on the HotSpot VM PermGen space and internal JIT related optimization objects.
  • The more applications you deploy to a single JVM, higher demand on native Heap.
  • Java threads require demand native memory.
  • Data caching not serialized to a disk or database will require extra memory from the OldGen space.
  • The java heap and native heap are in a race, the bigger your Java heap, smaller the native heap.  
Bytecode compilation uses native memory
Java applications run in the virtualized environment of the Java runtime, but the runtime itself is a native program written in a language (such as C) that consumes native resources, including native memory.
Every virtualized resource — including the Java heap and Java threads — must be stored in native memory, along with the data used by the virtual machine as it runs.
both the input (the bytecode) and the output (the executable code) from the JIT must also be stored in native memory.

Note 
 

  • JRockit and HotSpot are merging into one single JVM.
  • JDK 7 contains the first release of this converged JVM, which was one of the first steps was to start removing the PermGen concept in java 8.
  • The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace; similar to the Oracle JRockit and IBM JVM's.
  • Java Metaspace space setting is to be unbounded (dynamic resize) by default.

Manage Memory for permanent generation space (permgen)
If your JDeveloper IDE  is slow, you can increase the memory by: 
Edit the "jdev.con" file located at path "YOUR_Oracle_Home\jdeveloper\jdev\bin​"
and add following line:
AddVMOptionHotspot  -XX:MaxPermSize=1024M

also you can show consumed memory and force for garbage collection by adding the following line:
AddVMOption -DMainWindow.MemoryMonitorOn=true

See the file after modifying:

  • Now you can see a new bar added at Jdeveloper IDE, the arrow points to link that do job for Garbage Collecting:
  • Now you are more far from the error: OutOfMemoryError PermGen Space Error.
  •  JDeveloper 12.1.3 in test can be configured to develop/compile against JDK 8, and introduces support for JDK 8 language features.

http://javaeesupportpatterns.blogspot.com/2011/08/java-heap-space-hotspot-vm.html
https://blogs.oracle.com/henrik/entry/java_7_questions_answers
http://architects.dzone.com/articles/5-tips-proper-java-heap-size
http://architects.dzone.com/articles/5-tips-proper-java-heap-size
http://www.ibm.com/developerworks/linux/library/j-nativememory-linux/index.html
https://sourcevirtues.wordpress.com/2013/01/14/java-heap-space-and-native-heap-problems/

http://waslleysouza.com.br/en/2014/04/increase-the-performance-of-jdeveloper-11g/
http://www.oracle.com/technetwork/developer-tools/jdev/documentation/121300-cert-2164864.html
http://java.dzone.com/articles/java-8-permgen-metaspace
http://en.wikipedia.org/wiki/Java_virtual_machine

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...