Amazon

Tuesday, February 5, 2013

Freedom from darkness


Difference between Stack vs Heap in Java
==============================================================
Here are few differences between stack and heap memory in Java:
1) Main difference between heap and stack is that stack memory is used to store local variables and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable,  they are always created inside heap space in Java.
2) Each Thread in Java has there own stack which can be specified using -Xss JVM parameter, similarly you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of heap and -Xmx is maximum size of java heap. to learn more about JVM options see my post 10 JVM option Java programmer should know.
3) If there is no memory left in stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space. Read more about how to deal with java.lang.OutOfMemoryError  in my post 2 ways to solve OutOfMemoryError in Java.
4) If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is lot lesser than size of  heap memory in Java.
5) Variables stored in stacks are only visible to the owner Thread, while objects created in heap are visible to all thread. In other words stack memory is kind of private memory of Java Threads, while heap memory is shared among all threads.

Difference between IdentityHashMap and HashMap
===============================================
Though both HashMap and IdentityHashMap implements Map interface, have fail-fast Iterator and non synchronized collections, following are some key differences between HashMap and IdentityHashMap in Java.
1) Main difference between HashMap vs IdentityHashMap is that IdentityHashMap uses equality operator "==" for comparing keys and values inside Map while HashMap uses equals method for comparing keys and values.
2) Unlike HashMap, who uses hashcode to find bucket location, IdentityHashMap also doesn't use hashCode() instead it uses System.identityHashCode(object).
3) Another key difference between IdentityHashMap and HashMap in Java is Speed. Since IdentityHashMap doesn't use equals() its comparatively faster than HashMap for object with expensive equals() and hashCode().
4) One more difference between HashMap and IdentityHashMap is Immutability of key. One of the basic requirement to safely store Objects in HashMap is keys needs to be immutable, IdentityHashMap doesn't require keys to be immutable as it is not relied on equals and hashCode.
There is also a class called IdentityHashtable which is analogous to Hashtable in Java but it’s not part of standard JDK and available in com.sun... package.

Example of IdentityHashMap in Java
Here is an example of IdentityHashMap in Java which shows key difference between HashMap and IdentityHashMap in comparing Objects.  IdentityHashMap uses equality operator for comparison i instead of equals method in Java :

import java.util.IdentityHashMap;

/**
 * Java program to show difference between HashMap and IdentityHashMap in Java
 * @author Javin Paul
 */
public abstract class Testing {

    public static void main(String args[]) {
        IdentityHashMap identityMap = new IdentityHashMap();
      
        identityMap.put("sony", "bravia");
        identityMap.put(new String("sony"), "mobile");
      
        //size of identityMap should be 2 here because two strings are different objects
        System.out.println("Size of IdentityHashMap: " + identityMap.size());
        System.out.println("IdentityHashMap: " + identityMap);
      
        identityMap.put("sony", "videogame");
      
         //size of identityMap still should be 2 because "sony" and "sony" is same object
        System.out.println("Size of IdentityHashMap: " + identityMap.size());
        System.out.println("IdentityHashMap: " + identityMap);
    
    }
}

Output
Size of IdentityHashMap: 2
IdentityHashMap: {sony=bravia, sony=mobile}
Size of IdentityHashMap: 2
IdentityHashMap: {sony=videogame, sony=mobile}


When you assign an array to a previously declared array reference, the array you're assigning must be the same dimension as the reference you're assigning it to.
When you assign one primitive(a) variable to another(b), the contents of the right-hand variable are copied and but if we change the contents of either a or b, the other variable won't be affected.
static method cannot access an instance (non-static) variable or a non-static method.
Instance variables and objects live on the heap. Local variables live on the stack.
--> The default constructor has the same access modifier as the class.
--> The default constructor has no arguments.
--> The default constructor includes a no-arg call to the super constructor.

Constructors are never inherited. They aren't methods. They can't be overridden.
transient and volatile modifiers only applies to instance variables.
In a class, Calling a constructor from a method is illegal. Constructor can only be called from another constructor.
There are no final objects, only final references. A final reference still allows you to modify the state of the object it refers to, but you can't modify the reference variable to make it refer to a different object.
Classes can have only public or default access. Class declared private will not compile.
There are no final objects, only final references. A final reference still allows you to modify the state of the object it refers to, but you can't modify the reference variable to make it refer to a different object.
declaring final a List variable as 
private final List l = new ArrayList(); 
Can I do l.add("a"); in constructor?
Correlated and NonCorrelated Subquery- 
============================
1.In case of correlated subquery inner query depends on outer query while in case of noncorrelated query inner query or subquery doesn't depends on outer query and run by its own.
No-Correlated Query
=============
mysql> SELECT COMPANY FROM Stock WHERE LISTED_ON_EXCHANGE IN (SELECT RIC FROM Market WHERE COUNTRY='United States' OR COUNTRY= 'INDIA');
Correlated Query
============
mysql> SELECT m.NAME FROM Market m WHERE m.RIC = (SELECT s.LISTED_ON_EXCHANGE FROM Stock s WHERE s.LISTED_ON_EXCHANGE=m.RIC);
2.In case of correlated subquery, outer query executed before inner query or subquery while in case of NonCorrelated subquery inner query executes before outer query.
3.Correlated Sub-queries are slower than non correlated subquery and should be avoided in favor of sql joins.
4.Common example of correlated subquery is using exits and not exists keyword while non correlated query mostly use IN or NOT IN keywords.

Can we synchronize constructors?
HashCode Collision in HashMap: In case of hashCode collision, equals method is applied in same bucket with existing elements, if equals method return true, new value is applied on the old key value combination, if equals return false new entry is made with new key value in same bucket. Sample code below. I have created a custom object to be used as key in hashMap. Its hasCode will be the length of member variable name, i.e. tow different objects having different values but same length will be having same hashCode but their equals will return false.

import java.util.*;

public class HashTest{
public static void main(String[] args) {
Map map = new HashMap();
System.out.println(1);
MyObj newOne1 = new MyObj("one");
MyObj newOne3 = new MyObj("tre1");
System.out.println(2);

MyObj newOne2 = new MyObj("two");
System.out.println(3);

map.put(newOne1, "one");
System.out.println(4);

map.put(newOne2, "newOne");
System.out.println(5);

map.put(newOne3, "tre");
System.out.println(6);

System.out.println("Map is :"+map);
}
}

class MyObj{
String name = null;
public MyObj(String s){
name = s;
}

public int hashCode(){
System.out.println("Adding hash of -->"+name);
return name.length();//so that strings having same length but different value will return same hashCode
}

public boolean equals(Object o){

MyObj m = (MyObj)o;
System.out.println("equals called-->"+name+"="+m.name);

if(name.equals(m.name))return true;

return false;
}
}

============Output =======================
1
2
3
Adding hash of -->one
4
Adding hash of -->two
equals called-->two=one
5
Adding hash of -->tre1
6
Adding hash of -->two
Adding hash of -->one
Adding hash of -->tre1
Map is :{MyObj@3=newOne, MyObj@3=one, MyObj@4=tre}
EJB 3.0. Choosing Between a Local or Remote Client View
The following considerations should be taken into account in determining whether a local or remote access should be used for an enterprise bean.
• The remote programming model provides location independence and flexibility with regard to the distribution of components in the deployment environment. It provides a loose coupling between the client and the bean.
• Remote calls involve pass-by-value. This copy semantics provides a layer of isolation between caller and callee, and protects against the inadvertant modification of data. The client and the bean may be programmed to assume this parameter copying.
• Remote calls are potentially expensive. They involve network latency, overhead of the client and server software stacks, argument copying, etc. Remote calls are typically programmed in a coarse-grained manner with few interactions between the client and bean.
• The objects that are passed as parameters on remote calls must be serializable.
• When the EJB 2.1 and earlier remote home and remote component interfaces are used, the narrowing of remote types requires the use of javax.rmi.PortableRemoteObject.narrow rather than Java language casts.
• Remote calls may involve error cases due to communication, resource usage on other servers, etc., which are not expected in local calls. When the EJB 2.1 and earlier remote home and remote component interfaces are used, the client has to explicitly program handlers for handling the java.rmi.RemoteException.
• Because of the overhead of the remote programming model, it is typically used for relatively coarse-grained component access.
• Local calls involve pass-by-reference. The client and the bean may be programmed to rely on pass-by-reference semantics. For example, a client may have a large document which it wants to pass on to the bean to modify, and the bean further passes on. In the local programming model the sharing of state is possible. On the other hand, when the bean wants to return a data structure to the client but the bean does not want the client to modify it, the bean explicitly copies the data structure before returning it, while in the remote programming model the bean does not copy the data structure because it assumes that the system will do the copy.
• Because local calls involve pass-by-reference, the local client and the enterprise bean providing the local client view are collocated.
• The collocation entailed by the local programming model means that the enterprise bean cannot be deployed on a node different from that of its client—thus restricting the distribution of components.
• Because the local programming model provides more lightweight access to a component, it better supports more fine-grained component access.
Taken from EJB3.0 Specs








Primitive, Serializavble, Array or Colllection of primitive or serializables and Remote Objects are ship-able across the network for EJB calls.
Object's serialized copy is shipped over network while calling a method of EJB, while in case of local method call, objects reference is copied as method parameter.
javax.ejb.RemoteException is a checked exception.
Using Thread join() method
=====================
The join() method of a Thread instance can be used to "join" the start of a thread's execution to the end of another thread's execution so that a thread will not start running until another thread has ended. If join() is called on a Thread instance, the currently running thread will block until the Thread instance has finished executing.
We can illustrate this with an example. The RunnableJob class implements Runnable. Its run() method displays the current thread's name and the time at which the run() method is executed. It then sleeps for 1 second.

public class RunnableJob implements Runnable {

@Override
public void run() {
Thread thread = Thread.currentThread();
System.out.println("RunnableJob is being run by " + thread.getName() + " at " + new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

The ThreadExample class creates a RunnableJob object. It creates 4 threads named "T1", "T2", "T3", and "T4" with the RunnableJob object. It calls start() and then join() on each thread, in order. This blocks the execution of the current (main) thread from proceeding until the thread has completed. This means that the main thread will block for 1 second at each join(), since the RunnableJob sleeps for 1 second. Following this, ThreadExample creates 4 more threads, "T5", "T6", "T7", and "T8". This time, no joins are called on these threads, so the main thread will not block.

public class ThreadExample {

public static void main(String[] args) throws InterruptedException {

RunnableJob runnableJob = new RunnableJob();

Thread thread1 = new Thread(runnableJob, "T1");
Thread thread2 = new Thread(runnableJob, "T2");
Thread thread3 = new Thread(runnableJob, "T3");
Thread thread4 = new Thread(runnableJob, "T4");

thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
thread3.join();
thread4.start();
thread4.join();

Thread thread5 = new Thread(runnableJob, "T5");
Thread thread6 = new Thread(runnableJob, "T6");
Thread thread7 = new Thread(runnableJob, "T7");
Thread thread8 = new Thread(runnableJob, "T8");

thread5.start();
thread6.start();
thread7.start();
thread8.start();

}

}

The console output of the execution of ThreadExample is shown here. Notice from the times displayed that we indeed see that T1, T2, T3, and T4 are all separated by 1 second delays. Also, notice that there are no delays for T5, T6, T7, and T8. Also, notice that T7 executes RunnableJob's run() method before T6. This occurred since there is no guarantee as to the order that T5, T6, T7, and T8 will execute the job code.

RunnableJob is being run by T1 at Wed Nov 28 19:38:39 IST 2012
RunnableJob is being run by T2 at Wed Nov 28 19:38:40 IST 2012
RunnableJob is being run by T3 at Wed Nov 28 19:38:41 IST 2012
RunnableJob is being run by T4 at Wed Nov 28 19:38:42 IST 2012
RunnableJob is being run by T5 at Wed Nov 28 19:38:43 IST 2012
Hello World!-->main
RunnableJob is being run by T6 at Wed Nov 28 19:38:43 IST 2012
RunnableJob is being run by T7 at Wed Nov 28 19:38:43 IST 2012
RunnableJob is being run by T8 at Wed Nov 28 19:38:43 IST 2012

Use list.size() for browsing an ArrayList instead of using list.iterator(). Treating ArrayList like an array gives better performance than treating it as LinkedList.

No comments:

Post a Comment

Amazon Best Sellors

Weblogic - Server Creation - Issues

Datasource creation using python script.  Python Script was failing after creating Datasource. From UI Admin Console, if I try to activat...