Sunday, 31 July 2016

Java Junction - Learn Java By Exmaples


Java 5 BlockingQueue Features and Usage

BlockingQueue-

The BlockingQueue extends Queue.

Important Methods of Blocking Queue are-

Insert-NonBlockingQueue
1-add() - It will add specified element into BlockingQueue.No Blcoks behaviour methods apply with this method.If element will be added into BlockingQueue successful ly it will return true ,if not then will throw the exception “IllegalStateException”
2-offer(e)-true/false-will return true if element will be added ,if not added will return the false.If you will try to add Null then will throw the
exception NullPointerExceptiin

Insert Blocking
3-put(e)-Its a blocking operation ,if not space will be available ,it will wait -and as it will find the space ,it will add the specified element .
This method returns void and will throws exception NullPointerExceptiin if pass Null.
4-offer(e,long,TimeUnit)-Will wait upto specified timeunit if space is not available.If when space will be available during TimeUnnit ,it will
add and return true,if time will be elapsed then will return false.


Retrieval - Non BlockingQueue

1-peek()-  will return the head element and will not remove the Head, returned Null if no element exist.
2-poll()-   will return the head element and will removed the head., returned Null if no element exist.

Retrieval-Blocking
3-poll (long, TimeUnit)-Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.
4-take ()-It will wait until an element will be available.

int drainTo(Collection<? super E> c);
Removes all available elements from this queue and adds them to the given collection. This operation may be more efficient than repeatedly polling this queue. A failure encountered while attempting to add elements to collection c may result in elements being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue to itself result in IllegalArgumentException. Further, the behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

int drainTo(Collection<? super E> c,int maxElements);
Removes at most the given number of available elements from this queue and adds them to the given collection. A failure encountered while attempting to add elements to collection c may result in elements being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue to itself result in IllegalArgumentException. Further, the behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

Scenarios Where I Have used It-

Also we can use it in producer-consumer type problems
Where i have used LinkedBlockingQueue.?

How this solve the problems-
We are receiving multiples files on shared directory from an application.
A thread search the location and if files are available ,their main task is to

1)Reading the files
2)Parsed the files
3)-Format the files.
4)-Hit the URL of application -for each and every number.
5)-Save all data into database.
6)-and delete the files from shared directory and move it to backup  directory .

 Approach One-If we will create the one thread then it will take no lime to do all activities,
 because saving the data into DB will take time and hitting the application URL  will taking also times. So we come to things that ,we will read all files currently available on path.
 We have created six thread for six task and 5 LinkedBlockingQueue . All six thread are running independently.

 1)FileReaderThread - will read all files and copied those file into another directory and update database for files has been received now and it will put(File file) into LinkedBlockingQueue ,another thread(2) which read the file from LinkedBlockingQueue by using take() method and searched the
picked file from copied location (where thread one copied those files).after parsing the files it will update the DB and copied those files from directory to another directory,Now thread 3 will start their execution and read file from LinkedBlockingQueue and find it on Location (from here Thread2 copied the files).So here is best use of LinkedBlockingQueue and last thread will delete file from base-location where the file received initially.If any things goes wrong our server shutdown or any misshapen occurWe can start our execution from same point where we lost previously.because file status are also saving into DB

DIFFERENCE BETWEEN ADD() and OFFER()::
Add() means that if no space is available in queue ,it will throw exception(Exception in thread "main" java.lang.IllegalStateException: Queue full) while in case of offer() it will not throw any exception ,it will return a special values-‘FALSE’,In case of no space is available.
capacity restrictions- it means that queue capacity which we give at time of BlockingQueue creation.
Throws exception
Special value
add
offer
remove
poll
get
peek

Add(E e) Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an Exception if no space is currently available.


Offer() Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(E), which can fail to insert an element only by throwing an exception. 
Questions-
Re-entrant Locking-Why it come? What is problem with synchronize keyword.
Ans-
Let suppose one thread T1 is executing within a synchronized block and another thread T2 want to access the lock to execute same block. How T2 will know that someone (T1) is already being busy with block.

No solution was there - T2 will go to suspended state and when T1 will finish their execution it will notify then only t2 can know that resource is free now.

When one thread is executing in one method and call two more method like.

Synchronized {
obj.method1 ();
}
Method1 () {
Call method2 ();
}
Method2 () {
Sys (“Done!”);
}
If thread1 want to release the lock in method 2 it was not possible, t1 will come back to synchronized block and release lock by coming out the synchronized block.


Two Important Feature Not Available with Synchronized

1-Synchronized blocks don’t offer any mechanism to query the status of “waiting queue” of threads for a particular resource.

2-The synchronized block have to be present within the same method. A synchronized block cannot start in one method and end in another.

The synchronized block must be fully contained within a single method. A Lock can have it’s calls to lock() and unlock() in separate methods.

Difference between Lock Interface and synchronized keyword

The main differences between a Lock and a synchronized block are:
1) Having a timeout trying to get access to a synchronized block is not possible. Using Lock.tryLock(long timeout, TimeUnit timeUnit), it is possible.
Java concurrency lib implementations provide additional functionality over the use of synchronized, they providing a non-blocking attempt to acquire a lock (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly(), and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)).
A Lock class is quite different from that of the implicit monitor lock, it can provide guaranteed ordering, reentrant usage and deadlock detection.
An example of some ReentrantLocks using tryLock() :

What is Non-Blocking Attempt to acquire the lock?

Generally when we want to get a lock in Java, there was a method using synchronized? We call it on object like synchronized (object).Currently if lock is not available (some another thread already acquired) then your thread will go to block state. It is call Blocking Attempt to acquired lock.
When we invoked synchronized (object), and if your thread does not get lock and also not going to block state,means that it will not wait to release the lock, this is called Non-Blocking way of lock acquired. While this functionality is provided with synchronized keyword, after some year with jdk1.5 they introduced a new feature we called it Reentrant lock class. Its provide those functionality which you are demanding above.
Its provide this behavior in 3 flavor (3 method).

1)-tryLock()-if lock is available ,it provide the calling thread if no lock available then  thread would not be locked (this feature not available with synchronized keyword).

2)-lockInterruptibly ()- If lock is available its provide to calling thread, if not then it will be blocked .Blocked but it can be interrupted ,to come out from block state.

3)-tryLock(long ms,TIMEUNIT)- it lock is available its provided to calling thread ,if not then it will go to Block state for MS (milliseconds) which provide in parameter. After MS time, it will come out from block state.
Example-        
Runnable r = new Runnable() {
 @Override
 public void run() {
boolean lockAcquired = false;
try {
lockAcquired = lock.tryLock(1000*3,TimeUnit.MILLISECONDS);
System.out.println(lockAcquired + " lock acquired by " + Thread.currentThread().getName());
if (lockAcquired) {
Thread.sleep(1000 * 10);
} else {
                        System.out.println("I hav'not found the lock " + Thread.currentThread().getName());
 }
 } catch (InterruptedException e) {
                                                            // TODO Auto-generated catch block
  e.printStackTrace();
} finally {
                                                            if (lockAcquired) {
                                                                        lock.unlock();
                                                                        System.out.println("Unlocked By " + Thread.currentThread().getName());
                                                            }
                                                }

                                    }
                        };
                        Thread t1 = new Thread(r, "Thread1");
                        Thread t2 = new Thread(r, "Thread2");