Tuesday, December 11, 2012

Where are variables stored in Java, Stack or Heap?


A primitive variable “holds” directly his value itself. Examples of a primitive variable :  int i, long l;

A reference variable “holds” the reference (4 bytes on 32-bit JVMs, 8 bytes on 64-bit JVMs) who refers to an object. Examples of a reference variable : Student s, Date d;

local variable : a variable created in a method, the method parameter included.
instance variable : a variable that belongs to the instance of an object
class variable :  a variable that belongs to the class

public static void main(String args[]){
int a = 1;
Integer b = 2 ;
Student c = new Student();
c.setName(“kewei”);
}

public class Student {
int age = 27;
Date birthday = new Date();
String name;

public void setName(String nameParam) {
this.name = nameParam;
}
// ...
}

a is a primitive variable.
b is a reference variable (not object) who refers to an Integer object.
c is a reference variable (not object) who refers to a Student object.
age is a primitive variable.
birthday is a reference variable (not object) who refers to a Date object.

So where are all these variables stored, on the heap or on the stack? The answer is simple.

All local variables (primitive and reference variables) are stored on the stack. Everything else are stored on the heap.

All objects are stored on the heap.
All instance variables (primitive and reference variables) are stored on the heap too, since they are part of the object.
All class variables are stored on the heap too.

Stack is created for each individual thread. In this example, there is only one stack (the stack calls main() method). For multithread programs, there will be multiple stacks.

Analyze:
a, b are stored on the stack because they are local variables. c will also be stored on the stack because it is a local variable (at the same time, it is a reference variable). However, the student object that c refers to is stored on the heap. age is stored on the heap, because it is part of that student object. birthday is stored on the heap for the same reason (birthday is an instance variable, part of that student object). The date object that birthday refers to is also stored on the heap. name is also stored on the heap. nameParam is stored on the stack, because it is a local variable.

Wednesday, December 5, 2012

Why nonfair lock is faster than fair lock (java.util.concurrent.locks.Lock) in Java Concurrency


This is the nonfair scenario:
When a thread B asks to hold a lock, if the lock is already taken by another thread A. Then the thread B will be suspended. After thread A finished his job, it releases the lock, then thread B is resumed. However, B needs a period of time to be able to actually run it's task from where it was suspended. And this period of time could be relatively long compared to another thread C who is asking for that exact same lock at the same time. If C could acquire the lock, does C's job and release the lock before B even "wakes up" (the time between B's resumed and B's able to actually run), then it's a win-win situation for B and C. Because C gets the lock and has it's job done and releases the lock, while B's "waking up" and B gets the lock no later than it otherwise would have.

In the fair scenario:
The C will be queued after B.

To set the fairness of a Lock, one can use the parametered constructor:
Lock lock = new ReentrantLock(true); //true for fair, false for nonfair

Monday, July 23, 2012

How object in Java is initialized

1. A class is loaded when it is used for the first time, it is loaded from the class file (Ex. Student.class). If this class has a base class, the base class will be loaded before this class. 

2. Next, the static initialization in the base class is performed which initialize the static fields of the base class, and then the static initialization of this (derived) class kicks in, which makes sure that the base class static members have been initialized properly in case that derived class static initialization depend on them. Static initialization takes place only once.

3. Storage is allocated for this new object on the heap.

4. Storage is wiped to zero, all primitive fields of the base class and the derived class are set to their default values, which is zero or false, all reference fields are set to  null.

5. If there are any initialization at the definition of fields of the base class, it should take place at this point.

6. Execute the constructor of the base class.

7. The same steps 5 - 6 occur for the derived class.

Monday, July 9, 2012

Java Generics assignment sheet


raw type <------ any
any <------ raw type
<?> <------ any
<? extends T> <------ <T> and <? extends T>
<? super T> <------ <T> and <? super T>
<------: assign (assign from right to left)
any: all different variations of the generic class, including raw type and <T> and <?> and <? extends T> and <? super T>.
Example:


public class Main {


/**
* @param args
*/
public static void main(String[] args) {

List listRaw = new ArrayList();
List<Student> listQualified = new ArrayList<Student>();
List<?> listUnbounded = new ArrayList<Student>();
List<? extends Student> listUpBounded = new ArrayList<Student>();
List<? super Student> listDownBounded = new ArrayList<Student>();

// List raw type can take all different variations of List, for compatibility reason.
List rawList1 = listRaw;
List rawList2 = listQualified;
List rawList3 = listUnbounded;
List rawList4 = listUpBounded;
List rawList5 = listDownBounded;

// All different variations of List can take List raw type, for compatibility reason
listRaw = rawList1;
listQualified = rawList2;
listUnbounded = rawList3;
listUpBounded = rawList4;
listDownBounded = rawList5;

// List unbounded wildcard can take All different variations of List
List<?> wildcardList1 = listRaw;
List<?> wildcardList2 = listQualified;
List<?> wildcardList3 = listUnbounded;
List<?> wildcardList4 = listUpBounded;
List<?> wildcardList5 = listDownBounded;

// List subtype wildcard can take <T> and <? extends T> (and as mentioned above raw type)
List<? extends Student> subTypeWildcartList1 = listQualified;
List<? extends Student> subTypeWildcartList2 = listUpBounded;

// List supertype wildcard can take <T> and <? super T> (and as mentioned above raw type)
List<? super Student> superTypeWildcartList1 = listQualified;
List<? super Student> superTypeWildcartList2 = listDownBounded;

// You cannot create generic class instance with any form of wildcard
// List listNotAllowed1 = new ArrayList<?>();
// List listNotAllowed2 = new ArrayList<? extends Student>();
// List listNotAllowed3 = new ArrayList<? super Student>();

// An "exact" type of List (no wildcards) in a generic method argument can take all different variations of List.
// The return type is the same as calling the list.get(0),
// which is Object for List, List<?> and List<? super T>, and T for List<T> and List<? extends T>.
Object objectRaw = getFirstElement(listRaw);
Student studentQualified = getFirstElement(listQualified);
Object objectUnbounded = getFirstElement(listUnbounded);
Student studentUpBounded = getFirstElement(listUpBounded);
Object objectDownBounded = getFirstElement(listDownBounded);
}

public static <T> T getFirstElement(List<T> list) {
T t = list.get(0);
return t;
}
}

Sunday, July 8, 2012

Java Generics Wildcards explained


Given a generic class, like List<T>, or any generic class:
When using this generic class, for example:
    • List<Student> students = StudentFactory.getStudents();
    • or
    • public class StudentList implements List<Student> {...}
    • or
    • List<? extends Student> students = StudentFactory.getStudents();
    • or
    • List<? super Student> students = StudentFactory.getStudents();
    • or
    • etc.
public class StudentFactory {
public static List<Student> getStudents() {
return Arrays.asList(new Student("Student"));
}
}
1.In the case of using <? extends Student>
    • If a method takes a parameter of type T in the generic class definition (in this case, add(T t) of List<T>), we cannot call this method. (except by passing a null, which is not interesting)
    • If a method returns type T in the generic class definition (in this case, T get(int index) of List<T>), calling this method returns Student.
2.In the case of using <? super Student>
    • If a method takes a parameter of type T in the generic class definition (in this case,  add(T t) of List<T>), we can call this method by passing any subtype of Student.
    • If a method returns type T in the generic class definition (T get(int index) of List<T>), calling this method returns Object.
Explanations:
For case #1, List<? extends Student> means a list of any sub-type of Student.
students can point to a List<MathStudent>, or to a List<HistoryStudent>. That is to say, a List<MathStudent> can be ‘upcasted’ to a List<? extends Student>. If a method using type T accepted others to call it with type T, in this case T is Student. Inside the method, we could do something like assigning a HistoryStudent to MathStudent, which will surely cause an ClassCastException. So the compiler refuses calling these kind of methods using T at compile-time to do avoid this run-time exception. That’s kind of one of the important purpose of Generic. But it’s safe to call a method which returns a T since, we are sure that it returns MathStudent or HistoryStudent or Student. Whether it’s a MathStudent or a HistoryStudent or a Student, it’s always a Student.
For case #2, List<? super Student> means a list of any type that Student derived From, such as People, and People’s father class, etc. 
students can point to a List<People>, (suppose that Student extends People) or a list of any base-type of Student, but students cannot point to List<MathStudent>, or List<HistoryStudent>, or a list of any sub-type of Student. That is to say, a List<People> can be ‘upcasted’ to a List<? super Student>, but List<MathStudent> cannot be ‘upcasted’ to a List<? super Student>. Methods using type T  are allowed to be called with type T or any subtype of T, in this case, T is Student. because it’s safe. Inside the method, you can assign Student or MathStudent or HistoryStudent  to Student/People (or to any father class of Student). But when a method returns type T, it cannot be sure which base class of Student it returns, so it returns Object.