Saturday, July 27, 2013

Java : How HashMap stores and returns element

Hashing technique is useful in searching exact data in very short time.
In Java Collection Framework, Hashmap class provides functionality to store data using hashing techniques.
Here is how HashMap works internally.

Following main parameters are used to store data in HashMap:
  • Internal static class Entry which contains following variables
    • Key
    • Value
    • Next element
    • Hash value
  • Array of Entry objects (Bucket)
  • Threshold (Initial capacity * load factor)


While putting element in HashMap:
·         If key is null, it allows putting single value against null key. If you are trying to add another value against null key, it returns existing value in HashMap against null key and stores new value against null key.
o   Entry Object is stored at Bucket location 0. Hash value is also zero for null key.


·         How Value is stored against key in HashMap:
  •       Internal hash function is used to calculate hash value for hashcode of key. Hashcode of key is passed to hash function to get hash value.
  • Bucket index is found based on hash value and length of bucket. (Bucket is array which is used to store data. Data is Entry objects which contains key, value, next object and hash values). Bucket index = hash value & (bucket size-1). Bitwise and operator is used to find out index value.
  • Iterator is used to iterate over Entry objects at given index (if exists) to check if same key is already exists by comparing hash value and object equality using equals function. If same key is found, new value is stored against key and old value is returned.

Tuesday, July 16, 2013

JMS overview and sample standalone example

JMS API is used to allow applications to create, send, receive messages. It is mostly used in enterprise distributed systems (J2EE applications) for processing data asynchronously. It consists of
JMS API architecture
Messaging domain
Messaging receiver

JMS API Architecture:
JMS application consists of :

  1. JMS provider:  Messaging system that implements JMS interfaces and provide admin and control features
  2. JMS Client: Programs that produce and consume messages.
  3. Messages: objects that are transferred between JMS clients to communicate information.
  4. Administered Objects: pre configured JMS objects created by JMS administrator to be used by clients. Two kind of objects are destinations and connection factories.


There are 2 types of approaches for messaging- Point to point and Publish/subscribe.

  • Point to Point messaging: Based on message queue, message sender and message receiver. Message is addressed to specific queue. Queues retain all message until it is consumed by receiver or until message expires.
  • Publish/Subscribe messaging: In Pub/Sub messaging, message producer sends message to Topic. Message is delivered to receivers who have subscribed to that topic.

Apache ActiveMQ, Weblogic, OpenJMS, IBM Websphere MQ  are few examples of JMS provider implementations.
Below sample example shows simple standalone example of  JMS point to point messaging where administered objects (server configuration) are not used. You need Apache ActiveMQ jars to run this program.

Sample TestJMS.java file:

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQQueue;


public class TestJMS {

public static void main(String[] args) {

try {
//Start JMS service
BrokerService broker = new BrokerService();
broker.addConnector("tcp://localhost:61616");
broker.start();


ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");

Connection conn = connectionFactory.createConnection();

Queue queue = new ActiveMQQueue("testQueue");

Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

//Message Producer
MessageProducer prod = session.createProducer(queue);
//Message consumer
MessageConsumer consumer = session.createConsumer(queue);

TextMessage msg = session.createTextMessage("Hello JMS");
conn.start();
prod.send(msg);

Message message = null;
while((message = consumer.receiveNoWait()) != null){
if(message != null){
System.out.println("Message received:"+((TextMessage)message).getText());
}
}

conn.close();
broker.stop();

} catch (Exception e) {
e.printStackTrace();
}

}
}


Output of program:
Message received:Hello JMS

You can download ActiveMQ at : http://activemq.apache.org/

I have used "activemq-all-5.6.0.jar" as Build path library to run above application.

Thursday, July 4, 2013

Java: Thread Basics and Questions

Here are few general questions and answers related to Threads in Java

1. What is thread?
--> Thread is lightweight process which has its own stack trace but share resources.

2. Types of Thread:
--> Daemon thread and User thread : JVM exits when all user threads complete. It does not care whether daemon threads are complete or not.

3. How can we create Thread in java
--> a)  By extending Thread class
      b) By Implementing Runnable interface
Implementing Runnable is preferred because extending a Thread is meant to create specialized version of Class Thread where we may need some special behaviour. And We always instantiate thread by creating new instance of Thread class.

4. How to start a new thread?
--> by calling start() method of thread instance.

5. Explain different Thread states:
--> New : When thread instance is created and start method is not yet invoked. Thread t = new Thread(Runnable r);
Runnable: When thread is eligible to run but execution is not started. Threads enters in runnable state for first time when start() method is called. Thread also enters in runnable state after coming back from blocked, waiting, sleeping state.
Running: When scheduler picks thread for execution from runnable pool.
Waiting/Sleeping/Blocking: When thread is still alive but not eligible to run. Thread is not runnable but it might come to runnable when particular event happens.
Dead: Thread is dead when its run method completes. Once thread is dead, it cannot be invoke again by calling start(). It will generate runtime exception. Thread object is still valid object but not valid for separate thread of execution.

6. What is yield() method of Thread:
--> yield() method make currently running thread back to runnable pool to get other threads in runnable pool to get chance. But it is not guaranteed. Same thread can be picked up for execution by thread scheduler. When yield() is called. Thread goes from Running to Runnable state.

7. What is join() method:
--> Let one thread to join at the end of another thread. when t.join() is called. Currently running thread to join at the end of t. It means that currently running thread is blocked till t thread is complete.

8. When Currently running thread leaves running state:
a. When thread is complete. (run method is complete)
b. Thread can not acquire lock on object whose method it is trying to call.
c. When scheduler decides to move thread from running to runnable state.
d. Call to wait() on object

9. How can you prevent more than one threads to access code in Java
--> Using synchronization. We can use either synchronized method or synchronized block so that only one thread can access that method/block of code at a time.

10. How synchronization works
--> Synchronization work with lock on object. Every object in java has built in lock. When non-static method is synchronized, Thread which is running the code acquires lock on object which is calling method. No other thread can call synchronized method for that object unless current thread comes out of sync. method.
When synchronized method completes, thread releases lock so that other threads can call synchronized method on that object. Same applies for Synchronized block.
We declare synchronized block with synchronized(object){ }. We can pass any object as parameter to synchronized block. Thread acquires lock on that object. If we pass "this" as parameter to synchronized block, current instance of that class is locked.
Static methods can be synchronized. There is class instance (only one instance) of every class on which thread acquires lock.

Note: wait() method gives up lock while sleep(), yield(),join(), notify() keeps lock.

11. How thread interact with each other.
--> Using wait(), notify(), notifyAll(). Note that these methods should be called from synchronized block/method.

Wednesday, July 3, 2013

Object Oriented Programming Basic Concepts

Object oriented programming is useful for many aspects:
1. Code reuse.
2. Better design


Encapsulation: Hiding data and behaviour of an Object and provide interface (public methods) to outside objects to access data. It helps in preventing users from setting objects state directly which can cause inconsistency.

Inheritance: Way to establish relationship between objects. Here class inherit properties and method of parent class. Inheritance is termed as "Is a relationship" (Parent-Child relationship)

Polymorphism: Means many forms. Similar type of objects can behave differently for same message.
It is tightly coupled with Inheritance. Parent class provide interface(method) which is implemented differently by different child classes.