Fail-fast and Fail-safe iterators in java

Iterators are used to iterate or traverse over collections in java. The iterators can be fail-fast and fail-safe.
Fail-fast iterators throw exceptions at runtime (called the ConcurrentModificationException) if the collection is being modified while iterating over it.
Fail-safe iterators are those which do not throw exception if being modified while iterating because they work over the clone of the collection rather than working on the actual collection.

Iterator which iterate on HashMap, ArrayList classes are some examples of fail-fast Iterator.
Iterator which iterate on ConcurrentHashMap, CopyOnWriteArrayList classes are examples of fail-safe Iterator.

Understand with an Example !

1. Example of Fail-fast iterator

import java.util.ArrayList;
import java.util.Iterator;

public class FailFastIteratorTest {

public static void main(String[] args) {
	ArrayList<String> list = new ArrayList<>();
	list.add("john1");
	list.add("john2");
	list.add("john3");
	list.add("john4");
	list.add("john5");

	System.out.println(list);

	Iterator<String> iterator = list.iterator();
	while (iterator.hasNext()){
		if(iterator.next().equals("john3"))
		{
			list.remove("john3");
		}
	}
	System.out.println(list);
 }
}

OUTPUT

[john1, john2, john3, john4, john5]
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)

Problem

The problem here is that you are trying to remove an element “john3” from the list while iterating over it therefore this will lead to ConcurrentModificationException.

How to overcome it ?

So instead of list.remove(“john3”) use iterator.remove() method in the condition

while (iterator.hasNext()){
	if(iterator.next().equals("john3"))
	{
		iterator.remove();
	}
}

OUTPUT

[john1, john2, john3, john4, john5]
[john1, john2, john4, john5]

Using iterator’s remove() method you will not get any such Exception.

Important Fact :

  1. If you wish to use iterators for traversing a collection and then you intend to remove elements from that collection while iteration, then prefer using iterators remove() method as it doesn’t throw ConcurrentModificationException.
  2. There is another way to avoid exception, use fail-safe iterator collections instead, we will look into it below.

2. Example of Fail-safe iterator

As we read earlier, the fail-safe iterators do not throw concurrent modification exception because they work or iterate on the clone of the collection and not
on the actual.

But, There are a couple of drawbacks:

  1. Fail safe iterators does not always guarantee updated data, after the iterator is made if any modification is done on the collection will not reflect in the iterator as it works on the clone.
  2. One overhead is of memory and time used in creating a clone of collection to work on.

I. Example of CopyOnWriteArrayList :

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class FailSafeIteratorTest {

    public static void main(String[] args) {

        List<String> list = new CopyOnWriteArrayList<>();
        list.add("john1");
        list.add("john2");
        list.add("john3");
        list.add("john4");
        list.add("john5");

        System.out.println(list);

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().equals("john3")) {
                list.remove("john3");
            }
        }
        System.out.println(list);
    }
}

OUTPUT

[john1, john2, john3, john4, john5]
[john1, john2, john4, john5]

Here you will observe, on using fail safe iterator on CopyOnWriteArrayList it will not throw any exception.

II. Example of ConcurrentHashMap :

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

public class FailSafeIteratorTest {

    public static void main(String[] args) {

        ConcurrentHashMap<Integer,String> map = new ConcurrentHashMap<>();
        map.put(1,"one");
        map.put(2,"two");
        map.put(3,"three");
        map.put(4,"four");

        System.out.println(map);

        Iterator<Integer> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            int key = iterator.next();
            System.out.println(key + " : " + map.get(key));
            map.put(5,"five");
        }
        System.out.println(map);
    }
}

OUTPUT

{1=one, 2=two, 3=three, 4=four}
1 : one
2 : two
3 : three
4 : four
5 : five
{1=one, 2=two, 3=three, 4=four, 5=five}

Here you will observe, on using fail safe iterator on ConcurrentHashMap it will not throw any exception.

3. Difference between Fail-fast and Fail-safe iterators

Fail-fast IteratorFail-safe Iterator
This kind of iterator throws ConcurrentModificationException when iterating over a collection.This kind of iterator does not throw Exception when iterating over a collection.
It iterates on the original collection.It iterates over the copy of original collection and not on the actual collection.
There is no extra memory and time overhead like fail safe iterators as they operate on actual collection.It has an overhead of extra memory and time as it works over the copy of actual collection.
Examples are HashMap, ArrayList.Examples are ConcurrentHashMap, CopyOnWriteArrayList

4. How Iterators work internally ?

Initially in the internal implementation a variable called expectedModCount is equal to modCount which is zero.

int expectedModCount = modCount;

If there is any change done in the collection, the modCOunt will change and then an exception is thrown, by calling a method checkForComodification().

final void checkForComodification() {
     if (modCount != expectedModCount)
	throw new ConcurrentModificationException();
}

Summary

In this article we learnt about Fail-fast and Fail-safe iterators, we also learnt them with examples, it’s differences and internal working.
Hope you liked the article !


Java Threads | Multithreading in java

Life cycle of a Thread (Thread States)

NewRunnableRunningNon-Runnable (Blocked)Terminated

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

  1. ) New The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
  2. ) Runnable The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
  3. ) Running The thread is in running state if the thread scheduler has selected it.
  4. ) Non-Runnable (Blocked) This is the state when the thread is still alive, but is currently not eligible to run.
  5. ) Terminated A thread is in terminated or dead state when its run() method exits.

How to create thread

There are two ways to create a thread:By extending Thread classBy implementing Runnable interface

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:Thread()Thread(String name)Thread(Runnable r)Thread(Runnable r,String name)

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

public void run() : is used to perform action for a thread.

Starting a thread : start() method of Thread class is used to start a newly created thread.

It performs following tasks: A new thread starts(with new callstack). The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run() method will run.
1) Java Thread Example – by extending Thread class

      
      class Multi extends Thread{ 
      public void run(){ 
      System.out.println("thread is running..."); 
      } 
      public static void main(String args[]){ 
      Multi t1=new Multi(); 
      t1.start(); 
       } 
      } 
      Output:thread is running...
      

2) Java Thread Example – by implementing Runnable interface

      
      class Multi3 implements Runnable{ 
      public void run(){ 
      System.out.println("thread is running..."); 
      } 

      public static void main(String args[]){ 
      Multi3 m1=new Multi3(); 
      Thread t1 =new Thread(m1); 
      t1.start(); 
       } 
      } 
      Output:thread is running...
      

If you are not extending the Thread class,your class object would not be treated as a thread object. So you need to explicitly create Thread class object. We are passing the object of your class that implements Runnable so that your class run() method may execute.

Thread Scheduler in Java

Thread scheduler in java is the part of the JVM that decides which thread should run. There is no guarantee that which runnable thread will be chosen to run by the thread scheduler. Only one thread at a time can run in a single process. The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

Difference between preemptive scheduling and time slicing

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Deadlock in java

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.

Can we start a thread twice ??

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

Let’s understand it by the example given below:

      
      public class TestThreadTwice1 extends Thread{ 
       public void run(){ 
         System.out.println("running..."); 
       } 
       public static void main(String args[]){ 
        TestThreadTwice1 t1=new TestThreadTwice1(); 
        t1.start(); 
        t1.start(); 
       } 
      } 
      Test it Now
             running
             Exception in thread "main" java.lang.IllegalThreadStateException
      

What if we call run() method directly instead start() method ?

Each thread starts in a separate call stack. Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack. It runs like a normal method, and does not calls the thread stack.

Multithreading in Java

Multithreading in java is a process of executing multiple threads simultaneously. Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don’t allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading

  1. ) It doesn’t block the user because threads are independent and you can perform multiple operations at same time.
  2. ) You can perform many operations together so it saves time.
  3. ) Threads are independent so it doesn’t affect other threads if exception occur in a single thread.

Java Executor Framework for Multithreading

Java executor framework exist from JDK 5 in concurrent package(java.uti.concurrent.Executor). It is used to run the Runnable objects without creating a new thread every time rather it reuses the already created threads from the thread pool. Since creating a thread in java is a very expensive process as there is a memory overhead.

Executors is a utility class that also provides useful methods to work with ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes through various factory methods.

Example: Java executor framework

A Runnable class, named WorkerThread.java:

      
package com.test.threadpool;

public class WorkerThread implements Runnable {
  
    private String command;
    
    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+
                          " Start. Command = "+command);
        processCommand();
        System.out.println(Thread.currentThread().getName()+
                          " End.");
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString(){
        return this.command;
    }
}
        

Below is the main class with Thread pool created using Executors Framework

In the above program, we are creating a fixed size thread pool of 5 worker threads. Then we are submitting 10 jobs to this pool, since the pool size is 5, it will start working on 5 jobs and other jobs will be in wait state, as soon as one of the job is finished, another job from the wait queue will be picked up by worker thread and get’s executed.

package com.programmertoday.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleThreadPool {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

OUTPUT :

pool-1-thread-2 Start. Command = 1
pool-1-thread-4 Start. Command = 3
pool-1-thread-1 Start. Command = 0
pool-1-thread-3 Start. Command = 2
pool-1-thread-5 Start. Command = 4
pool-1-thread-4 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-3 Start. Command = 8
pool-1-thread-2 End.
pool-1-thread-2 Start. Command = 9
pool-1-thread-1 Start. Command = 7
pool-1-thread-5 Start. Command = 6
pool-1-thread-4 Start. Command = 5
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-3 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
Finished all threads
       

Summary

In this article we learnt about Java Multithreading, life cycle of a thread, how to create a thread, thread schedulers, executor framework and more.
Hope you liked the article !


Java collection Sorting Interfaces

These sorting interfaces are found in java.lang package

Sorting of Collections: using

  1. Comparable Interface : used for sorting
    1. String objects
    2. Wrapper class objects
    3. User-defined class objects
  2. Comparator Interface : used for sorting
    1. User-defined class objects

Comparable Interface


Java Comparable interface is used to sort or order the objects of the user-defined class. This interface contains only one method named compareTo(Object). It provides a single sorting sequence only i.e. you can sort the elements on the basis of single data member only. For example, it may be rollno, name, age or anything else.

public int compareTo(Object obj): It is used to compare the current object with the specified object. It returns

  1. positive integer, if the current object is greater than the specified object.
  2. negative integer, if the current object is less than the specified object.
  3. zero, if the current object is equal to the specified object.

Note : String class and Wrapper classes implement the Comparable interface by default. So if you store the objects of string or wrapper classes in a list, set or map, it will be Comparable by default.Example :

Of the Comparable interface that sorts the list elements on the basis of age.

                  
class Student implements Comparable<Student>{  
  int rollno;  
  String name;  
  int age;  
  Student(int rollno,String name,int age){  
  this.rollno=rollno;  
  this.name=name;  
  this.age=age;  
}  
  
public int compareTo(Student st){  
  if(age==st.age)  
    return 0;  
    else if(age>st.age)  
    return 1;  
    else  
    return -1;  
  }  
}  

import java.util.*;  
public class TestSort1{  
public static void main(String args[]){  
  ArrayList<Student> al=new ArrayList<Student>();  
  al.add(new Student(101,"Vijay",23));  
  al.add(new Student(106,"Ajay",27));  
  al.add(new Student(105,"Jai",21));  
  
Collections.sort(al);  
for(Student st:al){  
    System.out.println(st.rollno+" "+st.name+" "+st.age);  
    }  
  }  
} 

Comparator Interface


This interface contains 2 methods compare(Object obj1,Object obj2) and equals(Object element). It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data member, for example, rollno, name, age or anything else.

public void sort(List list, Comparator c): is used to sort the elements of List by the given Comparator.

  1. positive integer, if the current object is greater than the specified object.
  2. negative integer, if the current object is less than the specified object.
  3. zero, if the current object is equal to the specified object.

Note : String class and Wrapper classes implement the Comparable interface by default. So if you store the objects of string or wrapper classes in a list, set or map, it will be Comparable by default.Example :

Of the Comparable interface that sorts the list elements on the basis of age.

                  
class Student{  
  int rollno;  
  String name;  
  int age;  
  Student(int rollno,String name,int age){  
  this.rollno=rollno;  
  this.name=name;  
  this.age=age;  
  }  
}  

import java.util.*;  
class AgeComparator implements Comparator<Student>{  
  public int compare(Student s1,Student s2){  
    if(s1.age==s2.age)  
    return 0;  
    else if(s1.age>s2.age)  
    return 1;  
    else  
    return -1;  
  }  
}  

import java.util.*;  
import java.io.*;  
class Simple{  
public static void main(String args[]){  
  
ArrayList<Student> al=new ArrayList<Student>();  
al.add(new Student(101,"Vijay",23));  
al.add(new Student(106,"Ajay",27));  
al.add(new Student(105,"Jai",21));  
  
System.out.println("Sorting by Name");  
  
Collections.sort(al,new NameComparator());  
for(Student st: al){  
System.out.println(st.rollno+" "+st.name+" "+st.age);  
}  
  
System.out.println("Sorting by age");  
  
Collections.sort(al,new AgeComparator());  
for(Student st: al){  
System.out.println(st.rollno+" "+st.name+" "+st.age);  
}  
}  

}  

Summary

In this article we learnt about Java collections sorting and its various types. We learnt about Comparable and Comparator interface.
Hope you liked the article !


Java – Custom Exceptions in java

In java you have already seen some predefined classes such as NullPointerException, ArithmeticException these exceptions get triggered on certain defined conditions within their class. Meaning ? when there is a null value being computed or being used java throws an exception at run time and these can be caught using catch block.

Similarly in java you can create custom exceptions also called user defined exceptions.

You can create your own custom exceptions which can be triggered on your defined conditions using throw keyword.

Usage : Why to create Custom Exception at all ?

Sometimes you need an exception to be handled based on your set of conditions and rules in the code, in such cases you create your own custom exceptions.

Simple ! So How to create Custom Exception ?

Below we will create a custom exception class called MyCustomException

    
public class TestException{

public static void main(String args[]){
    try{
      int a=11;
      if (a>10) {
            throw new MyCustomException(a); //used throw keyword to throw Exception
      }
    }
    catch(MyCustomException e){
      System.out.println(e) ;
    }
  }

}
class MyCustomException extends Exception{

    int b;

    public MyCustomException(int a) {
      b=a;
    }

    public String toString() {
      return "The number "+b+" is out of range";
    }
}       

OUTPUT

The number 11 is out of range

Summary

So here we are, we hope now you are confident and know how to create custom Exceptions in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.


Java – Exception Handling

It is a resizable array or a dynamic array. It uses this dynamic array mechanism to store its elements. ArrayList class is found in the java.util package in java.

There are two types of errors:

  1. Compile time errors
  2. Runtime errors

Compile time errors : Often categorized as syntax(when syntax is not correct) and semantic(when syntax is correct but the usage is not) errors.

Example –

syntax error : when you write floa a; instead of float a; or

semantic error : when you declare a variable float a; again after few lines, float a;

Runtime errors : Also called as Exception errors. Exception is an unexpected event that disrupts the normal flow of execution of a program.

Example – ArithmeticException, NullPointerException, NumberFormatException, ArrayIndexOutOfBoundsException

Arising of exceptions is something which is not in developers control.

Why do we need to Handle Exceptions ?

In Real world life scenario consider a case when you have made an application which has a User Interface and it connects to a database and database goes down because of maintenance or is locked because of some failure.

How will a user/customer come to know that there is an issue with the database, will you throw an error on there face ? or catch this database exception and handle it gracefully showing proper message to the user.

So if you don’t wanna let your user/customer run away from your application by seeing the technical errors which they do not understand we handle the exceptions gracefully by catching these exceptions and return meaningful messages to the user/customer of the downtime or anything like that OR a better way for this example is to switch to a backup database in case the main database is not responding/throwing error.

How to Handle Exceptions ?

To handle a situation like in above scenario, we try to write a code which can handle this kind of exception. In this example of database failure we write a code to switch to another backup database so that our application is up and running without any interuption.

It can be written in an “if else block” as well BUT what if there is some other database exception which you did not forsee or cover in your code, what do you do then ? For this reason we need an Exception Handler.

Java and many other languages provides Exception Handling classes/frameworks which can handle it gracefully.

Try Catch finally Block

Try block : Program statements that you think can raise exceptions are contained within a try block.

Catch block : Write the code to handle exception in graceful manner.

Finally block : Write the code which you want should execute at any cost no matter exception is raised or not.
Example : closing session/database/file connection after execution of program.

Syntax of writing try-catch-finally block

try{
    //Code where you expect an exception would occur
  }
catch (exceptiontype name){
    //Code to handle the exception if it occurs
  }
finally{
    // example : connection.close();
  }

Actual Example :

public static void main(String[] args) {
    int a=0;
    int b=10;
    System.out.println("before dividing");
    try {
      System.out.println(b/a);
    }
    catch(ArithmeticException e) {
      e.printStackTrace();
    }
    System.out.println("after dividing");
}

OUTPUT

    
before dividing
java.lang.ArithmeticException: / by zero
  at com.test.exceptions.TestExceptions.main(TestExceptions.java:10)
after dividing    

Example : with finally block

public static void main(String[] args) {
    int a=0;
    int b=10;
    System.out.println("before dividing");
    try {
    System.out.println(b/a);
    }
    catch(ArithmeticException e) {
      e.printStackTrace();
    }
    finally {
      System.out.println("after dividing finally block");
    }
}

OUTPUT

before dividing
java.lang.ArithmeticException: / by zero
at com.test.exceptions.TestExceptions.main(TestExceptions.java:10)
after dividing finally block   

Hierarchy of ArrayList class

Diagram comes here

Java Exception Keywords

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause.

Difference between Checked and Unchecked Exceptions

In java there are 2 types of exceptions.

  • Checked Exceptions
  • Unchecked Exceptions
S.NoCheckedUnchecked
1Checked exceptions are the exceptions which are checked at compile time.Unchecked are the exceptions that are not checked at compiled time.
2IOExceptions class is compile time.In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

Summary

So here we are, we hope now you are confident and know how to use Exceptions in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.


Priority Queue Data Structure

Priority queue data structure in java is an implementation of queue interface.

Unlike other queue implementation classes(Like linkedlist) , priority queue does not orders elements based on insertion order (first in first out) but instead orders the elements according to their priorities. Element with the least priority is the head of the queue and is always removed first. Element with highest priority is always removed last.

Priority of the element is decided based on their natural ordering or using a comparator if provided in the constructor while creating the priority queue. In case no comparator is specified in the constructor, priority queue orders the elements based on their natural ordering.

  • Head is always the element with least priority.
  • Priority queue does not allow insertion of null element.
  • To insert objects of user defined class, priority queue expects the objects to belong to a class implementing comparable interface.
  • Priority queue does not allow insertion of non-comparable objects. This is because to decide the priority of any element which is inserted it has to be compared with existing elements in the queue.

Example : Priority Queue Data Structure

1.) creating priority queue

PriorityQueue<String> pq = new PriorityQueue<String>();
// Add elements to piority queue
pq.add("Marie");
pq.add("Jasmine");
pq.add("Rose");

System.out.println("priority queue : " + pq);
            

OUTPUT

priority queue: [Jasmine, Marie, Rose]
            

2.) remove elements from priority queue

System.out.println("priority queue: " + pq);

// check head element of the queue
String head = pq.peek();
System.out.println("head of the queue:" + head);

// remove element from the queue
pq.poll();
System.out.println("queue after removing an element: " + pq);
            

OUTPUT

priority queue: [Jasmine, Marie, Rose]
head of the queue: Jasmine
queue after removing an element: [Marie, Rose]
            

Summary

In this article we learnt about the Priority Queue Data Structure using Java. For better understanding we looked into some code snippets of queues add, peek & poll operations.
Hope you liked the article !


Queue Data Structure

Queue data structure is a part of java collection framework. It is available as an interface under java.util package. Queues are generally based on First in first out (FIFO) principle which means the element inserted first will be removed first and element inserted last will be removed last. This unique property of queue makes it useful to store number of elements before processing them.

Queue is an interface in java which is implemented by many classes like PriorityQueue, Deque, LinkedList. Not all implementation classes follow the first in fist out ordering but follows some or the other kind of ordering. For example; Priority queue orders the element according to their priorities.

Representation of Queue data structure

The first element in a queue is called the head. All the elements added after head are inserted at the tail of the queue. Queues can be thought of having one open end for insertion and other end for removal of elements.

Step by step insertion and deletion in a queue

As Queue extends java collection framework, it supports all the collection framework functions including add, remove, element. Apart from these Queue also provides additional functions for insertion, extraction, and inspection. This means that these functions are present in two forms in Queue where one form throws exception if the operation fails (this is default behaviour of collection framework inherited methods) and the other form added in Queue interface which returns null if the operation fails.

OperationThrows ExceptionReturns value(true/false/null)
Insertadd(e)offer(e)
Removeremove(e)poll()
Examineelement(e)peek()

Add Vs Offer() – offer method is used to insert an element in the queue if possible. This method returns true if element is successfully added and returns false if it fails to add an element. On the contrary, the add method which is inherited from collection framework throws an exception in case it fails to add an element to the queue. It is must to have an exceptional handling mechanism while calling add method. But not while calling offer method.

remove() Vs poll() – remove and poll methods are used to remove and return the head of the queue. In case the queue is empty poll methods throws exception but remove returns null.

Element and peek() – element and peek method are used to get the value of head element. It does not remove the head of the queue. Incase of empty queue , peek method throws an exception whereas element method returns null.

Example of Queue data structure

Linked List is one implementation of Queue.

import java.util.Queue;

public class QueueExample {
  
  public static void main(String[] args) {

    Queue<String> queue = new java.util.LinkedList<String>();

    // Add elements to the queue
    queue.add("Rose");
    queue.add("Mary");
    queue.add("Jasmine");

    System.out.println("original queue : " + queue);

    // check head element of the queue
    String head = queue.peek();
    System.out.println("head of the queue :" + head);

    // remove element from the queue
    queue.poll();
    System.out.println("queue after removing an element: " + queue);
  }
}            
            

OUTPUT

original queue : [Rose, Mary, Jasmine]
head of the queue :Rose
queue after removing an element: [Mary, Jasmine]            
          

Summary

In this article we learnt about the Queue Data Structure using Java. For better understanding we looked into some code snippets of queues add, peek & poll operations.
Hope you liked the article !


Stack in Java

A Stack is a data structure known in many programming languages. It is based on last in first out (LIFO) principle. In a stack, the element that is inserted last or most recent will be accessed first.

The stack can be imagined as a Stack of plates placed on top of one another. The plate that is placed last in the stack will always be on the top of the stack and will be picked up first. Elements in a stack can be inserted or accessed only from one end called as top of the stack. Any new element in a stack can be added only to the top of the stack. If an element has to be removed from the stack it gets removed from the top.

Functions available in Stack :

  1. push(element) – to add an element to the top of a stack
  2. pop() – to remove an element from top of a stack
  3. peek() – to see the top element in the stack
  4. isEmpty() to check if the stack is empty

Create and add elements to a stack

 
import java.util.Stack;

public class StackMain {
	
	public static void main(String[] args) {

		// Create Stack
		Stack<String> stack =new Stack<>();
		
		// Push elements to stack
		stack.push("A");
		stack.push("B");
		stack.push("C");
		stack.push("D");
		
		// Print elements in a stack
		System.out.println("stack : " + stack);

    }
} 
  

OUTPUT

Stack : [A,B,C,D]
    

Check the top element in a stack

 
// check the top most element in a stack
String top = stack.peek();
System.out.println("stack.peek() : " + top);
        

OUTPUT

stack.peek() : D
    

Remove elements from a stack

 
// Pop out elements in a stack
String firstFromTop = stack.pop();
System.out.println("stack.pop() : " + firstFromTop);
System.out.println("stack after stack.pop() : " + stack);
System.out.println();


String secondFromTop = stack.pop();
System.out.println("stack.pop() : " + secondFromTop);
System.out.println("stack after stack.pop() : " + stack);

OUTPUT

stack.pop() : D
Stack after stack.pop() : [A, B, C]
  
stack.pop() : C
Stack after stack.pop() : [A, B]
  

Iterate over a Stack :

for(String element : stack){
  System.out.println("element : " + element);
}
System.out.println("Stack after iteration : " + stack);

OUTPUT

element : A
element : B
Stack after iteration : [A, B]
  

Uses of Stack

Stack is used in function calls as well as in recursive function calls.

Compilers use stacks to check for balanced parentheses.

Stack interview questions

Balanced Parentheses : check if each opening parentheses has a matching closing parentheses or not

Parentheses or brackets means any of [ , ] ,{ , } , ( , ) . 
The matching pairs of opening and closing brackets are
( and )
[ and ]
{ and }
  

Given a string, each opening bracket should have a matching closing bracket to its right-hand side. Also, any pair of matching brackets can enclose another pair of matching brackets of same or different type.

Examples of balanced parentheses

[ ]
{ [ ] }
{ { { } } }

Examples of imbalanced parantheses

[ )
{ [ } ]
{ { { } } 

Write a function to return YES if the string has balanced Parentheses and return NO if the Parentheses are not balanced.

APPROACH : to the above example

In a balanced Parentheses scenario, the first closing bracket at an index will have a matching opening bracket at index-1. Once the matching pair is found, if u remove this pair the next closing bracket at an index will have an opening matching bracket at index-1 and so on. So, based on this scenario we decided to use Stack as it’s a LIFO based data structure so that when we find a closing bracket we can look back at the last inserted bracket and remove it if it’s a matching bracket.

  1. Use stack data structure.
  2. Traverse the input string. If any opening bracket is found push it in the stack.
  3. If a closing bracket is found, pop from the top of the stack to see the last inserted bracket is matching or not.
  4. If step 3 returns a non-matching bracket , return NO. else continue string traversal and keep following steps 2 and 3.
  5. After complete traversal of the input string, check if Stack is empty. If yes Return YES else return NO.

Solution

import java.util.Stack;

public class BalancedBrackets {
  
    public static String isBalanced(String s) {
        Stack<Character> stack = new Stack<>();
        char input[] = s.toCharArray();

        for (int i = 0; i < input.length; i++) {
          char bracket = input[i];
          if (bracket == '{' || bracket == '[' || bracket == '(') {
                stack.push(bracket);
          }

          switch (bracket) {
          case '}':
                if (stack.isEmpty() || stack.peek() != '{') {
                      return "NO";
                }
                stack.pop();
                break;
          case ']':
                if (stack.isEmpty() || stack.peek() != '[') {
                      return "NO";
                }
                stack.pop();
                break;
          case ')':
              if (stack.isEmpty() || stack.peek() != '(') {
                      return "NO";
                }
                stack.pop();
                break;
          }
        }
          return (stack.empty()) ? "YES" : "NO";
    }
  
public static void main(String[] args) {

      String s = "{{()}[]}";
      String output = isBalanced(s);
      System.out.println(output);
}
          

Summary

In this article we learnt about the Stack Data Structure using Java. For better understanding we looked into some code snippets of stack push, peek & pop operations
Hope you liked the article !


Java – Collections Class

java.util.Collections class entirely consists of static methods. Since the methods are static hence called using class name

e.g: Collections.sort(list) – sorts the list in ascending order

e.g: Collections.min(list) – gives the minimum in the list

The important points about Java Collections class are:

  • Java Collection class supports the polymorphic algorithms that operate on collections.
  • Java Collection class throws a NullPointerException if the collections or class objects provided to them are null.
S.NoModifier & TypeMethodsDescriptions
1static <T> booleanaddAll()It is used to adds all of the specified elements to the specified collection.
2static <T> Queue<T>asLifoQueue()It returns a view of a Deque as a Last-in-first-out (LIFO) Queue.
3static <T> intbinarySearch()It searches the list for the specified object and returns their position in a sorted list.
4static <E> Collection<E>checkedCollection()It is used to returns a dynamically typesafe view of the specified collection.
5static <E> List<E>checkedList()It is used to returns a dynamically typesafe view of the specified list.
6static <K,V> Map<K,V>checkedMap()It is used to returns a dynamically typesafe view of the specified map.
7static <K,V> NavigableMap<K,V>checkedNavigableMap()It is used to returns a dynamically typesafe view of the specified navigable map.
8static <E> NavigableSet<E>checkedNavigableSet()It is used to returns a dynamically typesafe view of the specified navigable set.
9static <E> Queue<E>checkedQueue()It is used to returns a dynamically typesafe view of the specified queue.
10static <E> Set<E>checkedSet()It is used to returns a dynamically typesafe view of the specified set.
11static <K,V> SortedMap<K,V>checkedSortedMap()It is used to returns a dynamically typesafe view of the specified sorted map.
12static <E> SortedSet<E>checkedSortedSet()It is used to returns a dynamically typesafe view of the specified sorted set.
13static <T> voidcopy()It is used to copy all the elements from one list into another list.
14static booleandisjoint()It returns true if the two specified collections have no elements in common.
15static <T> Enumeration<T>emptyEnumeration()It is used to get an enumeration that has no elements.
16static <T> Iterator<T>emptyIterator()It is used to get an Iterator that has no elements.
17static <T> List<T>emptyList()It is used to get a List that has no elements.
18static <T> ListIterator<T>emptyListIterator()It is used to get a List Iterator that has no elements.
19static <K,V> Map<K,V>emptyMap()It returns an empty map which is immutable.
20static <K,V> NavigableMap<K,V>emptyNavigableMap()It returns an empty navigable map which is immutable.
21static <E> NavigableSet<E>emptyNavigableSet()It is used to get an empty navigable set which is immutable in nature.
22static <T> Set<T>emptySet()It is used to get the set that has no elements.
23static <K,V> SortedMap<K,V>emptySortedMap()It returns an empty sorted map which is immutable.
24static <E> SortedSet<E>emptySortedSet()It is used to get the sorted set that has no elements.
25static <T> Enumeration<T>enumeration()It is used to get the enumeration over the specified collection.
26static <T> voidfill()It is used to replace all of the elements of the specified list with the specified elements.
27static intfrequency()It is used to get the number of elements in the specified collection equal to the specified object.
28static intindexOfSubList()It is used to get the starting position of the first occurrence of the specified target list within the specified source list. It returns -1 if there is no such occurrence in the specified list.
29static intlastIndexOfSubList()It is used to get the starting position of the last occurrence of the specified target list within the specified source list. It returns -1 if there is no such occurrence in the specified list.
30static <T> ArrayList<T>list()It is used to get an array list containing the elements returned by the specified enumeration in the order in which they are returned by the enumeration.
31static <T extends Object & Comparable<? super T>> Tmax()It is used to get the maximum value of the given collection, according to the natural ordering of its elements.
32static <T extends Object & Comparable<? super T>> Tmin()It is used to get the minimum value of the given collection, according to the natural ordering of its elements.
33static <T> List<T>nCopies()It is used to get an immutable list consisting of n copies of the specified object.
34static <E> Set<E>newSetFromMap()It is used to return a set backed by the specified map.
35static <T> booleanreplaceAll()It is used to replace all occurrences of one specified value in a list with the other specified value.
36static voidreverse()It is used to reverse the order of the elements in the specified list.
37static <T> Comparator<T>reverseOrder()It is used to get the comparator that imposes the reverse of the natural ordering on a collection of objects which implement the Comparable interface.
38static voidrotate()It is used to rotate the elements in the specified list by a given distance.
39static voidshuffle()It is used to randomly reorders the specified list elements using a default randomness.
40static <T> Set<T>singleton()It is used to get an immutable set which contains only the specified object.
41static <T> List<T>singletonList()It is used to get an immutable list which contains only the specified object.
42static <K,V> Map<K,V>singletonMap()It is used to get an immutable map, mapping only the specified key to the specified value.
43static <T extends Comparable<? super T>>voidsort()It is used to sort the elements presents in the specified list of collection in ascending order.
44static voidswap()It is used to swap the elements at the specified positions in the specified list.
45static <T> Collection<T>synchronizedCollection()It is used to get a synchronized (thread-safe) collection backed by the specified collection.
46static <T> List<T>synchronizedList()It is used to get a synchronized (thread-safe) collection backed by the specified list.
47static <K,V> Map<K,V>synchronizedMap()It is used to get a synchronized (thread-safe) map backed by the specified map.
48static <K,V> NavigableMap<K,V>synchronizedNavigableMap()It is used to get a synchronized (thread-safe) navigable map backed by the specified navigable map.
49static <T> NavigableSet<T>synchronizedNavigableSet()It is used to get a synchronized (thread-safe) navigable set backed by the specified navigable set.
50static <T> Set<T>synchronizedSet()It is used to get a synchronized (thread-safe) set backed by the specified set.
51static <K,V> SortedMap<K,V>synchronizedSortedMap()It is used to get a synchronized (thread-safe) sorted map backed by the specified sorted map.
52static <T> SortedSet<T>synchronizedSortedSet()It is used to get a synchronized (thread-safe) sorted set backed by the specified sorted set.
53static <T> Collection<T>unmodifiableCollection()It is used to get an unmodifiable view of the specified collection.
54static <T> List<T>unmodifiableList()It is used to get an unmodifiable view of the specified list.
55static <K,V> Map<K,V>unmodifiableMap()It is used to get an unmodifiable view of the specified map.
56static <K,V> NavigableMap<K,V>unmodifiableNavigableMap()It is used to get an unmodifiable view of the specified navigable map.
57static <T> NavigableSet<T>unmodifiableNavigableSet()It is used to get an unmodifiable view of the specified navigable set.
58static <T> Set<T>unmodifiableSet()It is used to get an unmodifiable view of the specified set.
59static <K,V> SortedMap<K,V>unmodifiableSortedMap()It is used to get an unmodifiable view of the specified sorted map.
60static <T> SortedSet<T>unmodifiableSortedSet()It is used to get an unmodifiable view of the specified sorted set.

Java – ConcurrentHashMap Class

ConcurrentHashMap class is introduced in JDK 1.5, which implements ConcurrentMap as well as Serializable interface also.

This was introduced to handle situations like running in multithreaded environment and also it works fine when you try to modify map at runtime i.e. it allows modification at runtime and avoid ConcurrentModificationException.

When threads are involved, ConcurrentHashMap is a better option over a regular HashMap. The underlying data structure for ConcurrentHashMap is also the Hashtable.

It provides thread safety and allows concurrent access to the map

  • Concurrency-Level : Defines the number which is an estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this many threads. Default concurrency-level of ConcurrentHashMap is 16.
  • Load-Factor : It’s a threshold, used to control resizing.
  • Initial Capacity : The implementation performs internal sizing to accommodate these many elements.
  • Segments :A ConcurrentHashMap is divided into number of segments
  • Null cannot be inserted as key or value in ConcurrentHashMap.

Note : A ConcurrentHashMap has internal final class called Segment so we can say that ConcurrentHashMap is internally divided in segments of size 16, so at max 16 threads can work at a time. It means each thread can work on a each segment during high concurrency and atmost 16 threads can operate at max which simply maintains 16 locks to guard each bucket of the ConcurrentHashMap.

In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updation in object, thread must lock the particular segment in which thread want to operate.This type of locking mechanism is known as Segment locking or bucket locking. Hence at a time 16 updation operations can be performed by threads.

A method Highlight : putIfAbsent(K key, V value)

This method puts the key only if it is not already present in the map.

Coding Example
import java.util.concurrent.*;
class ExampleConcurrentHashMap {
    public static void main(String[] args)
    {
        ConcurrentHashMap chmap = new ConcurrentHashMap();
        chmap.put(1, "Hi");
        chmap.put(2, "Programmer");
        chmap.put(3, "Today");
  
        // Here we can't add “Whatsup” because key “2”
        // is already present in ConcurrentHashMap object
        chmap.putIfAbsent(2, "Whatsup");
  
        // Now we can add "Whatsup"
        chmap.putIfAbsent(4, "Whatsup");
          
        System.out.println(chmap);
    }
}
        

Output

{1=Hi, 2=Programmer, 3=Today, 4=Whatsup}

Constructors of ConcurrentHashMap

HashMap provides 5 constructors :

  • ConcurrentHashMap() : Creates a new, empty map with a default initial capacity (16), load factor (0.75) and concurrencyLevel (16).
  • ConcurrentHashMap(int initialCapacity) : Creates a new, empty map with the specified initial capacity, and with default load factor (0.75) and concurrencyLevel (16).
  • ConcurrentHashMap(int initialCapacity, float loadFactor) : Creates a new, empty map with the specified initial capacity and load factor and with the default concurrencyLevel (16).
  • ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) : Creates a new, empty map with the specified initial capacity, load factor and concurrency level.
  • ConcurrentHashMap(Map map) : Creates a new map with the same mappings as the given map.

When to use ConcurrentHashMap in Java

ConcurrentHashMap is best suited when you have multiple readers and few writer. The performance of ConcurrentHashMap effectively reduces if the writers are more than the readers.

But why does the performance reduces ? The reason for this is that you got to lock all portion of Map, and effectively each reader will wait for another writer, operating on that portion of Map. ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads.

Difference between ConcurrentHashMap and HashMap | when to you use what ?

S.NoConcurrentHashMapHashMap
1ConcurrentHashMap is thread-safe and can be used in a concurrent environment without external synchronization.Not thread-safe, not good for multithreaded functionalities
2in case of ConcurrentHashMap, thread-safety is achieved by dividing whole Map into different partition based upon Concurrency level and only locking particular portion instead of locking the whole Map.You can make HashMap synchronized by wrapping it on Collections.synchornizedMap(HashMap) which will return a collection which is almost equivalent to Hashtable, where every modification operation on Map is locked on Map object
3ConcurrentHashMap is more scalable and performs better than Synchronized HashMap in the multi-threaded environment.in Single threaded environment both HashMap and ConcurrentHashMap gives comparable performance, where HashMap only slightly better.
4Whereas In ConcurrentHashMap we wont get any exception while performing any modification at the time of Iteration.While one thread is Iterating the HashMap object, if other thread try to add/modify the contents of Object then we will get Run-time exception saying ConcurrentModificationException.

 Important Summary

  1. Choose concurrency level carefully as a significantly higher number can be a waste of time and space and the lower number may introduce thread contention in case writers over number concurrency level.
  2. Iterator returned by ConcurrentHashMap is weekly consistent, fail-safe and never throw ConcurrentModificationException. In Java.
  3. You can use ConcurrentHashMap in place of Hashtable but with caution as CHM doesn’t lock whole Map.