Posts

Showing posts from January, 2018

Multithreading - Locks

Traditional multithreaded programming comes with a single way to get the lock i.e. synchronized keyword. All the threads wait until a thread releases the lock i.e. leaves the synchronized block. With the new concurrent api, locks were introduced to give the following facilities : 1. You can try for acquiring a lock, if you get acquire it, if not, you do something else/wait as you wish. 2. You can specify for how much time you want to wait to acquire a lock. This is one of the ways to avoid deadlocks, since thread will not go in a wait state forever. 3. If multiple threads are waiting for a lock, we now have an option to define if the thread waiting for the longest time gets the lock. 4. synchronized keyword was applicable only at method level or block level, but now we have an option to use locks across multiple methods. The locks functionality is present in the java.util.concurrent.locks package starting JDK 1.5 The top interface here is Lock, which defines the basic mecha

Multithreading - Concurrency packages

The original multithreading support in Java does not provide high-level features such as locks, thread pools, execution managers, etc. Java intoduced these features in JDK 5 in the form of concurrent utilities in the java.util.concurrent packages. Following are the features of the concurrency utilities : 1. synchronizers (locks) 2. Executors 3. Concurrent collections 4. Fork/Join framework Before starting lets take a look at thread groups. Every thread in Java,including the main thread, belongs to a thread group. A thread group is a group of threads. In addition to threads, thread groups can also contain sub thread groups.  The usefulness of this concept is that we can do operations, like setting thread priority, on a bunch of threads together rather than doing that for individual threads. ThreadGroup comes with following methods to provide utilities : setMaxPriority() - Any thread added to the thread group will have this priority setDaemon() - sets all the threads in

Multithreading - Daemon Threads

Daemon threads are threads that run in the background. The best example for that is Garbage Collector. Java provides following methods related to daemon threads : 1. isDaemon() - check if the thread is a daemon thread 2. setDaemon() - set the thread to be a daemon thread By default, the main thread is not a daemon thread. All the child threads inherit the daemon nature from the thread that creates them. public class DaemonThreadExample { public static void main (String[] args) { MyThreadExtendingThreadClass t = new MyThreadExtendingThreadClass() ; t.setDaemon( true ) ; t.start() ; // check till how many outputs it generates on the console System. out .println(Thread. currentThread ().isDaemon()) ; System. out .println( "Main thread completed" ) ; } } Daemon threads are automatically terminated when all the non-daemon threads have finished execution. The example for daemon thread can be found  here

Multithreading - Interthread communication

Generally, when one thread has acquired a lock, then other threads need to wait for the lock to get released. So other threads keep on polling to see if the lock has been released and that they can acquire it. This results in a waste of CPU cycles. Java comes with a elegant solution to this. It provides wait (), notify () and notifyAll () methods that can be used for interthread communication without the need of polling. wait() - tells the calling thread to give up the monitor and go to sleep until some other thread calls                    notify() or notifyAll() method. notify() - wakes up the thread that called the wait() method on the object. notifyAll() - wakes up all the threads that called the wait() method on the object. One of them will get                      access. All the three methods are present in the Object class, hence are available to all the classes. These methods can be called from synchronized context only. In case, you try to call it outside synchroniz

Multithreading - thread execution methods

We would like to control the execution of thread i.e. prevent/suspend it from execution for some time or alter its execution. Java provides us with 3 methods to do so : 1. yield() 2. sleep() 3. join() 1. yield() Threads are executed based on priorities. Now some threads can be less important but may have normal priority. So it should be ok if those threads execute later and some priority thread can finish its execution first. In this scenario, yield() method comes useful. for ( int i= 0 ; i< 500 ; i++) { Thread. yield () ; System. out .println( "Main Thread running" ) ; } When a thread calls the yield() method, it tells the thread scheduler that it can pause its execution and that if there is any other higher priority thread, thread scheduler can give priority to its execution. 2. sleep() The sleep() method suspends a executing thread for specified time. MyThread t1 = new MyThread() ; t1.setName( "t1" ) ; t1.start() ; try { Thread.

Multithreading - Synchronization

When multiple threads need to access a shared resource, they need to ensure that, at a time, only single thread accesses the resource. The process by which this is achieved is called synchronization . Also, when multiple threads operate on the same object, that can lead to data corruption. This is also known as race condition . To prevent this, we need to use synchronization. Every object has a monitor that is a mutually exclusive lock for that object. When a thread owns the lock, it basically enters the monitor. All other threads will have to wait until the first thread exits the monitor. Java provides with synchronized keyword. It is applicable to methods and code blocks but not on classes and variables. Whenever a thread needs to acquire lock of an object, it simply calls the synchronized method of the object. To release the lock, it returns from the method or the code block. public synchronized void synchronizedPrinter (String name) { for ( int i= 0 ; i< 250 ; i+

Multithreading - ThreadPriority

Java provides us a way by which we can define priority for a thread. The acceptable values for thread priority are from 1 to 10. 1 being minimum, 10 being maximum. By default, normal priority is 5 and thread scheduler works based on that. Consider the following program : MyThreadExtendingThreadClass myThreadExtendingThreadClass = new MyThreadExtendingThreadClass() ; myThreadExtendingThreadClass.setPriority( 2 ) ; MyThreadImplementingRunnableInterface myThreadImplementingRunnableInterface = new MyThreadImplementingRunnableInterface() ; Thread thread = new Thread(myThreadImplementingRunnableInterface) ; thread.setPriority( 10 ) ; thread.start() ; myThreadExtendingThreadClass.start() ; If you execute this program , you will see that the threads now follow the assigned priority and the thread extended by Thread class executes after the thread implemented by Runnable completes. Also, note that if you give priority other than acceptable values, it throws an IllegalStateArgument

Multithreading - Creating your own thread

Java provides different ways of creating threads as follows : 1. Extending Thread Class We can extend the Thread class for creating our own custom Thread class and override its run () method as follows : public class MyThreadExtendingThreadClass extends Thread { @Override public void run () { for ( int i= 0 ; i< 100 ; i++) { System. out .println( "Child Thread by extending Thread : " + i) ; } } } Then in the main class, you can create a object of this class and call the start () method of the thread : MyThreadExtendingThreadClass myThreadExtendingThreadClass = new MyThreadExtendingThreadClass() ; myThreadExtendingThreadClass.start() ; When you call the start() method, it internally calls the run() method and creates a separate path of execution in the program. If you try to call the start() method multiple times, it will throw IllegalThreadStateException. What if you directly call run() instead of start(), in that ca

Multithreading in Java

Image
All computer operating systems allow us to perform multiple tasks at the same time. i.e. take notes in a notepad, IM, email, etc. Similarly, multithreading is doing multiple things within a program. Multithreading means multiple threads. Thread defines a separate path of execution in a program. A multithreaded program is one that contains two or more threads that run simultaneously. Multitasking involves multiple processes. Now every process has its own memory space. While in case of multithreading, all threads share the same memory space of the process in which they reside. Interprocess communication is expensive while interthread communication is cheaper. Lifecycle of a thread : The above diagram shows the lifecycle of a thread in Java. Thread has 5 states : 1. New - new thread created 2. Runnable - ready to run 3. Running - in running state 4. Blocked - in waiting state 5. Dead - execution completed All Java programs have a main thread of execution that starts

Collection Framework - When to use What

Here we will talk about when to use what from the bunch we get in the collection framework. Also we will explore the reasons for using them. Every class in the collection framework implements Cloneable and Serializable interfaces. If you need to frequently access objects in your collection, then ArrayList and Vector are the best choices. Why? Both these classes implement the RandomAccess interface which provides them the ability to access any random element with the same speed. ArrayList is a bad choice if we need to add or remove objects frequently. Reason being when you insert an object to an index, all the subsequent objects need to be displaced from their current positions. Secondly, everytime arraylist grows, it has to copy all the objects to the new list. Vector is a legacy class. It is thread-safe, i.e. at a time only single thread can perform operations on it. Hence there is a performance toll when compared to ArrayList. ArrayList, on the other hand, is not thread

Collection Framework - Utility classes

Collection framework provides 2 utility classes : Collections and Arrays 1. Collections The  default implementation of ArrayList is non-synchronized. What if we wanted a synchronized version of an ArrayList. Collections class provides a method for the same as below ; ArrayList arrayList = new ArrayList(); List synchronizedArrayList = Collections. synchronizedList (arrayList); The same thing holds true for sets and maps as well. Collections class provides methods : synchronizedSet () and synchronizedMap () respectively. Collection class also provides for implementation of sorting for collection classes which do not come with default sort mechanisms such as ArrayList. ArrayList arrayList = new ArrayList(); arrayList.add(25); arrayList.add(15); arrayList.add(0) ArrayList.add(100); Collections.sort(arrayList); //sorts in the natural sorting order. Collections.sort(arrayList, descendingComparator); //define your comparator and use it for sorting. There are many mo

Collection framework - Queue interface and its implementation classes

Queue is based on the underlying data structure queue which has FIFO pattern. Queue is used when we want to store the elements in a certain order before processing. Queue interface comes with the following methods : boolean offer(Object obj) - Attempts to add object to queue. If success, return true else false. Object peek() - returns the head element. null if queue empty. Object poll() - returns and removes the head element. returns null if queue empty. Object remove() - returns and removes the head element. throws exception if queue empty. Object element() - returns the head element. throws exception if queue empty. PriorityQueue is the implementation class of the Queue interface. It stores the elements based on certain sorting order. either natural sorting order or based on specified comparator based sorting order. PriorityQueue comes with the following constructors : PriorityQueue() - creates a queue with initial capacity of 11. PriorityQueue(int initialCapacity)

Collection Framework - Hashtable & Properties

Image
Hashtable is a legacy class. It is based on hash table data structure itself.  The main difference between other classes and Hashtable is that it doesnt allow null values. It is synchronized and thread-safe. Hashtable comes with the following constructors : Hashtable() - creates a default hash table with initial capacity of 11 and load factor 0.75 Hashtable(int initialCapacity) - creates hash table with specified initial capacity and load factor 0.75 Hashtable(int initialCapacity, int loadFactor) - creates hash table with specified initial  capacity &                                                                                  load factor Hashtable(Map m) - creates hash table from the specified map The values in the table are stored based on the hashcodes of the keys. If two keys have the same hash code, then the values are chained. Also if the hashtable has not reached its load factor, and we do not have a bucket for the hash code, then also the values are chained b

Collection Framework - SortedMap, NavigableMap and TreeMap

SortedMap is the child of Map interface. As was the case with SortedSet, SortedMap stores the keys based on a particular sorting order. SortedMap comes with methods similar to SortedSet as follows : firstKey() - returns first key lastKey() - returns last key headMap(key) - returns map of keys before the specified key tailMap(key) - returns map of keys after the specified key including it subMap(key) - returns map of keys between initial and final key including the initial key comparator() - returns use comparator else null Similar to NavigableSet, NavigableMap also provides with the methods for searching : lowerKey() lowerEntry() floorKey() floorEntry() ceilingKey() ceilingEntry() higherKey() higherEntry() pollFirstEntry() pollLastEntry() TreeMap is the implementation class of NavigableMap. It provides default constructor as well as comparator constructor. The working of TreeMap is similar to TreeSet. The example of TreeMap can be found  here

Collection Framework - HashMap, LinkedHashMap, IdentityHashMap and WeakHashMap

HashMap is based on the implementation of the hash table data structure. Now map is a key-value pair, so values are stored based on the hashcode of the keys. i.e. keys need to be unique. Similar to a HashSet, HashMap comes with the following constructors : HashMap() - creates hashmap with default size 16 and load factor 0.75 HashMap(Map<Key, Value> m) - creates hashmap from givn map HashMap(int initialCapacity) - creates hashmap with specified capacity and load factor 0.75 HashMap(int initialCapacity, float fillRatio) - creates hashmap with specified capacity and load factor The example for HashMap can be found  here LinkedHashMap is based on linkedlist and hashtable as was the case with LinkedHashSet. Insertion order is preserved. The example for LinkedHashMap can be found  here . The console output shows the exact functioning of the LinkedHashMap. Next is IdentityHashMap. For checking if the key exists or not, Java uses equals() method which basically means chec

Collection Framework - Map interface and its implementation classes

Image
Map is not a child interface of Collection interface. When we want to represent our objects as key-value pairs, Map is used. Map is a set of entries. 1 entry = 1 key-value pair. Entry is a interface inside Map interface. Map interface comes with the following methods : Object put(Object key, Object value) - add key-value pair to map and returns null if key didnt exist                                                                   else returns previous value void putAll(Map  m) - adds all the key/value pairs from m into the map. Object get(Object key) - returns the object against the key else null. Object remove(Object key) - returns the object against the key else null. boolean containsKey(Object key) boolean containsValue(Object key) void clear() boolean isEmpty() int size() Set entrySet() - returns the set of entries in the map Set keySet() - returns the set of keys Collection values() - returns values Implementation classes are : 1. HashMap 2. LinkedHashMa

Collection Framework - SortedSet, NavigableSet and TreeSet

SortedSet is a interface that extends the Set interface. As the name suggests, it contains certain methods specific to sorting. Duplicates not allowed, insertion order not preserved. Elements are stored in a sorted manner. For integers, they are stored in ascending order. For Strings, its alphabetical order. Custom objects need to implement Comparable interface. SortedSet has the following methods : first() - returns first element last() - returns last element headSet(median) - returns elements before the median element tailSet(median) - returns elements after the median element alongwith median element subSet(startElement, lastElement) - set of elements inclusive startelement excluding lastElement comparator() - returns comparator if you  have set a different rule for sorting. default null if you havent used any sorting. Now we also need the facility to navigate through the elements, and for this NavigableSet was introduced. It extends the SortedSet and in addition b

Collection Framework - HashSet And LinkedHashSet class

As ArrayLists use arrays as the underlying storage, in case of HashSet, hashtable is the datastructure that was implemented. HashSet stores objects based on their hashcodes. Duplicates are not allowed and since its stored based on hashcode, insertion order is not preserved. Hashing data structures comes with a initial capacity of 16  i.e. 2 power 4. There is one more terminology with regards to hashing data structures, load factor , i.e. when should a new hashset be created with double the capacity. Default load factor is 0.75 i.e. when 75% hashset is filled, a new larger hashset is created. HashSet comes with the following constructors : HashSet() - creates a hash set with a default initial capacity of 16 and load factor 0.75 HashSet(int initialCapacity) - creates a hash set with the specified initial capacity and load factor 0.75. HashSet(int initialCapacity, int loadFactor) - creates a hash set with the specified initial capacity and the specified load factor HashSet(

Collection Framework - Set Interface and its implementations

Image
Set interface extends the Collection Interface. So it has all the methods of the collection interface. The set is primarily based on the rule that no duplicates are allowed and we do not care about the insertion order. The set interface does not come with new methods. Although its implementation classes have their own implementations and methods. The implementation classes of the Set interface are as follows : 1. HashSet 2. LinkedHashSet 3. TreeSet (SortedSet and NavigableSet are interfaces)

Collection Framework - Cursors in Java

Java provides interfaces that are implemented by collection classes so that we can fetch elements one by one or iterate through the elements in the collection. The cursors provided by Java are : 1. Enumeration 2. Iterator 3. ListIterator 4. SplitIterator(introduced in Java 8) Before the introduction of cursors, what was the way we used to iterate through the collection? The traditional for loop!!! for(int i=0; i< coll.size;i++) {      System.out.println(coll.get(i)); } Enumeration It is a legacy interface that provides us the facility to traverse through the elements of the legacy classes one by one. The example for enumeration can be found  here Iterator Enumeration has 2 limitations : 1. Its only applicable to legacy classes 2. We do not have an option to remove element from collection while traversing The above two limitations were overcome by introduction of Iterator. Iterator is a universal cursor i.e. it is applicable to all the classes in the collecti

Collection Framework - Stack class

Image
Stack is again a legacy class. It is a impelementation of LIFO concept. It is a child class of Vector. What that means is it has all the features of a vector, in addition to that, it also defines its own methods for pushing and popping the elements. While storing it follows the index mechanism, but for searching it follows the offset as shown in the above figure. E.g. A is stored at 0 index, but if you search it will return 3 reason being you need to pop 3 times to get A out of stack. As vector, this was also reimplemented to include generics and implement the List interface. Stack comes with a default constructor only : Stack() and Stack<E>() The example for Stack class can be found here It shows the implementation of both list specific methods as well as push(), pop(), peek() methods along with Enumeration.

Collection Framework - Vector Class

Similar to ArrayList, Vector also implements dynamic arrays. The difference being Vector is synchronized. Vector is a legacy class. But with the introduction of collection and later JDK 5, Vector was reimplemented to support generics and implement the List interface. Vector also is initialized with an initial capacity of 10. It also operates same as ArrayList. Once the initial capacity is filled, a new Vector is created and all the elements are copied to the new object. The distinction being the new object created has twice the capacity of the original object. In case of arraylist, it used to be 50% more then the original object. Vector class comes with the following constructors : Vector() - default constructor that will have an initial capacity of 10. Vector(int initialCapacity) - creates a Vector object with the specified capacity Vector(int initialCapacity, int increment) - creates a Vector object with the specified capacity and once that capacity is exhausted, it increm

Collection Framework - LinkedList Class

Image
The implementation of LinkedList in Java is based on the doubly linked list datastructure. All the elements store the memory locations for the previous and the next elements with the exceptions being first and the last element. The first element doesnt store the previous node info and the last element doesnt store the next node info. In Java, LinkedList comes with two constructors : LinkedList() - default constructor LinkedList(Collection<? extends E> coll) - creates a linkedlist object from the given collection An example of linkedlist can be found  here Stack is a legacy class. We can even use LinkedList to implement Stack. Since it already provides addLast() and removeFirst() methods. Stack is based on LIFO (last in first out) Same thing holds true for Queue. We have  addLast(), removeFirst() methods for the same.

Collection Framework - ArrayList class

Image
Arrays are of fixed length. Once created they cannot grow or shrink. Collection framework provides ArrayList that supports dynamic arrays that can change in size as needed. Array Lists are created with an initial size of 10. When the size increases, a new array list is created and all the objects are copied to that, and reference is set to that arraylist. Similarly, when the objects are removed, size can be reduced. ArrayList comes with 3 constructors : ArrayList() - creates an arraylist with initialcapacity of 10. ArrayList(Collection<? extends E> coll) - creates an arraylist from any collection derived class like linkedlist, treeset, vector, etc. ArrayList(int initialCapacity) - creates an arraylist with the specified initial capacity. An example for all the above constructor types can be found  here Also starting with Java 5, Collection framework supports generics so the above example also shows that implementation as well.

Collection Framework - List Interface and its implementations

List  interface extends the Collection interface. So it has all the methods available in the collection interface. On top of it, below are the methods added in the List interface : Addition/Selection/Deletion methods : add(int index, Object o) - Add an object to a specified index addAll(int index, Collection coll) - Add a collection to a specified index remove(int index) - Remove an object from the index set(int index, Object o) - Set an object at a particular index get(int index) - Get an object at a particular  index Utility methods : indexOf(Object o) - Index of Object o lastIndexOf(Object o) - Since list support duplicates, this one returns the last index of o. listIterator() - returns a list iterator that can be used to iterate over the list. The implementations of List Interface are : 1. ArrayList 2. LinkedList 3. Vector 4. Stack

Collection Framework

Collection interface defines the most common methods useful for any collection object. Following are the methods :               Addition/Deletion methods : add(Object obj) - add a single object to the collection addAll(Collection coll) - add collection to the collection remove(Object obj) - remove single object from the collection removeAll(Collection coll) - remove collection from the collection clear() - remove all objects from the collection retainAll(Collection coll) - remove all objects except the objects in collection coll                Utility methods : isEmpty() - check if the collection is empty size() - get the size of the collection contains(Object obj) - check if object exists in the collection containsAll(Collection coll) - check if objects in collection coll exists in the collection toArray() - convert the collection into an array iterator() - returns an Iterator object that can be used to iterate through the collection As we saw in the previo

Collection Framework

Image
Collection Framework provides classes and interfaces that can be used to represent collections i.e. a group of objects. Interfaces in the Collection Framework Following are the interfaces provided by the Collection Framework : 1. Collection : - defines the most common methods which are applicable for any Collection object. 2. List : - Child interface of Collection. - represents group of objects - duplicates allowed - order of insertion preserved - Child classes : ArrayList, LinkedList, Vector->Stack 3. Set :  - Child interface of Collection. - represents group of objects - unique elements i.e. duplicates not allowed - insertion order not preserved - Child classes : HashSet, LinkedHashSet 4. SortedSet : - Child interface of Set - represents group of objects - unique elements i.e. duplicates not allowed - elements stored in a sorted order 5. NavigableSet : - Child interface of SortedSet - provides methods for navigating through the elements - Child clas

Collection Framework - Introduction

Collection typically stands for a group of things or people. In programming terms, you can think of it as a collection of data objects. Why Collections? Prior to introduction of collections framework, Array was used to group objects. Lets first see the limitations of Arrays and then see the offerings of the collections framework. Limitations of Arrays: - Fixed size : can lead to underutilization/overutilization based on demand - Can store same type of objects : int[] can have only int types; String[] can only store String objects. To overcome the above limitations, we make use of collections. 1. Collections are dynamically sized. 2. Collections can hold both same type as well as different type of objects. i.e. they can store both homogenous as well as heterogenous objects. Apart from the above points, collections are implemented based on data structures, so there are readymade implementations available like contains(), natural ordering of elements, etc. In case of arra