Monday, March 29, 2021

Java ArrayBlockingQueue With Examples

Java ArrayBlockingQueue which is an implementation of the BlockingQueue interface was added in Java 5 along with other concurrent utilities like CopyOnWriteArrayList, ReentrantReadWriteLock, Exchanger, CountDownLatch etc.

ArrayBlockingQueue in Java is a bounded blocking queue which internally uses an array to store elements. ArrayBlockingQueue orders elements in FIFO (first-in-first-out) order. When new elements are inserted, those are inserted at the tail of the queue. At the time of retrieval, elements are retrieved from the head of the queue.

Since ArrayBlockingQueue is bounded it means you can't add unlimited number of elements in it. ArrayBlockingQueue has to be created with some initial capacity and that capacity cannot be changed later. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.

Java ArrayBlockingQueue Constructors

  1. ArrayBlockingQueue(int capacity)- Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy.
  2. ArrayBlockingQueue(int capacity, boolean fair)- Creates an ArrayBlockingQueue with the given (fixed) capacity and the specified access policy. A queue created with fairness set to true grants access to waiting producer and consumer threads in FIFO order.
  3. ArrayBlockingQueue(int capacity, boolean fair, Collection<? extends E> c)- Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified access policy and initially containing the elements of the given collection, added in traversal order of the collection's iterator.

Sunday, March 28, 2021

Non-Blocking Algorithms in Java

In this tutorial we'll see what is Non-blocking algorithm and which data structures in Java are non-blocking.

In a multi-threading application if you use a lock or synchronization only one thread at any given time can get hold to the monitor and enter the critical section, all other threads wait for the lock to get free. Same way, if any data structure has to be used in a multi-threaded environment then it has to use some concurrent algorithm, if that concurrent algorithm allows only one thread at any given time and block all the others then that algorithm is a blocking algorithm. Examples- Synchronized ArrayList or HashMap, implementations of BlockingQueue interface like ArrayBlockingQueue or LinkedBlockingQueue use that kind of lock-based algorithm thus run the risk of blocking the threads (may be for ever).

If a thread holding the lock is waiting for some resource like I/O or delayed due to some other fault then other waiting threads will not make any progress. For example, If you are using an ArrayBlockingQueue, which is a bounded blocking queue, with capacity as 10. In that case if queue is full and another thread comes to put (using put() method) a value then the thread is blocked until some other thread takes (using take() method) a value out.

Non-blocking algorithm

To prevent the problems as stated above non-blocking algorithm based classes/data structures are introduced in Java starting Java 5. Some of the examples are atomic operation supporting classes like AtomicInteger, AtomicLong and Concurrent collection like ConcurrentLinkedQueue in Java.

An algorithm is called non-blocking if it doesn't block threads in such a way that only one thread has access to the data structure and all the other threads are waiting. Same way failure of any thread in a non-blocking algorithm doesn't mean failure or suspension of other threads.

Saturday, March 27, 2021

How to Create Deadlock in Java

This post is about writing a Java program to create deadlock in a multi-threaded application.

Deadlock can happen if there are nested synchronized blocks in your code. There are 2 things to note here-

  • Locks are acquired at object level.
  • Only that thread which has acquired the lock can enter the synchronized block.

Logic for the Java program is that there are two Thread classes ThreadA and ThreadB and there are two objects of the class DeadLckDemo. In both of these classes ThreadA and ThreadB there are nested synchronized blocks and the object reference provided in the blocks is reversed in both of those classes.

In one of the class if nested block is as-

  System.out.println("" + Thread.currentThread().getName());
    System.out.println("Reached here");

Then in other class it is like this-

  System.out.println("" + Thread.currentThread().getName());
    System.out.println("Reached here");

If two threads are started, one for ThreadA and another one for ThreadB. Thread t1 will acquire a lock on obj1 and enter the outer synchronized block. Meanwhile thread t2 will start and get a lock on obj2 and enter the outer block in ThreadB class. That's where both of these threads will enter in a deadlock.

Thursday, March 25, 2021

Varargs (Variable-length Arguments) in Java

varargs in Java short for variable-length arguments is a feature that allows the method to accept variable number of arguments (zero or more). With varargs it has become simple to create methods that need to take a variable number of arguments. The feature of variable argument (varargs) has been added in Java 5.

Syntax of varargs

A vararg in Java is specified by three ellipsis (three dots) after the data type, its general form is

return_type method_name(data_type ... variableName){

Wednesday, March 24, 2021

How to Run Threads in Sequence in Java

How to ensure that threads run in sequence is a very popular Java multi-threading interview question. Though it doesn’t make much sense practically to do that as you use threads so that processing can be done by many threads simultaneously. But you have to answer a question if asked in interview so this post tries to gives answer to that question "How to ensure threads run in sequence in Java".

So, if you are asked to answer the question “How can you make sure that Thread t1, t2 and t3 are executed in such a way that t2 starts after t1 finishes and t3 starts after executing t2”, you have to say, it can be done using join() method in Java.

join() method in Java

join() method is used when you want to wait for the thread to finish. Its general form is–

public final void join() throws InterruptedException
This method waits until the thread on which it is called terminates.

As you see from the description of the join() method if it is called on any thread it will wait until the thread on which it is called terminates. Armed with this info let’s see the Java code to ensure that threads run in sequence.

Tuesday, March 23, 2021

StringBuilder Class in Java With Examples

StringBuilder class in Java, added in Java 5, is a mutable (modifiable) sequence of characters just like StringBuffer class, which is in contrast to String class in Java which is an immutable sequence of characters. Thus in case of StringBuilder length and content of the sequence can be changed through certain method calls.

Internally StringBuilder class objects are treated like variable-length arrays that contain a sequence of characters.

StringBuilder class in Java provides an API compatible with StringBuffer, how it differs from StringBuffer is that StringBuilder in Java is not thread-safe whereas StringBuffer is thread-safe.

As per Java docs– StringBuilder class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Constructors in Java StringBuilder class

  • StringBuilder()- Constructs a string builder with no characters in it and an initial capacity of 16 characters.
  • StringBuilder(CharSequence seq)- Constructs a string builder that contains the same characters as the specified CharSequence.
  • StringBuilder(int capacity)- Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
  • StringBuilder(String str)- Constructs a string builder initialized to the contents of the specified string.

Monday, March 22, 2021

AtomicInteger in Java With Examples

AtomicInteger class in Java provides an int value that may be updated atomically. This class resides in the java.util.concurrent.atomic package which has classes that support lock-free, thread-safe programming on single variables. Apart from AtomicInteger some of the other classes are AtomicLong, AtomicReference, DoubleAccumulator.

How AtomicInteger class in Java works

The atomic variable classes in Java concurrency like AtomicInteger, AtomicLong uses non-blocking algorithm. These non-blocking algorithms use low-level atomic machine instructions such as compare-and-swap instead of locks to ensure data integrity under concurrent access.

Classes in this package java.util.concurrent.atomic provides methods that can get, set or compare value as an atomic operation. Atomic operations are performed as a single unit of task where all the operations succeed or none.There is no need to explicitly use any locking or synchronization as AtomicInteger supports lock-free, thread-safe programming on single variables.

Sunday, March 21, 2021

How to Create Password Protected Zip File in Java

This post shows how to create a password protected zip file in Java and also how to unzip a password protected zip file in Java.

Though Java provides an API ( for compressing and decompressing files in zip format but there is no option for setting password so you need to use a third party library for creating a password protected zip file.

Library used here is Zip4j. You can download the jar zip4j_1.3.2.jar from here- Ensure that it is added to your application’s class path.

You can also add the following Maven dependency to download the jars.


Zipping and unzipping password protected file in Java

In the code there are two methods compressWithPassword() and unCompressPasswordProtectedFiles(). compressWithPassword() method is used to create a password protected zipped file where as unCompressPasswordProtectedFiles() method is used to unzip a password protected zipped file.

Saturday, March 20, 2021

How to Run a Shell Script From Java Program

This post talks about how you can execute a shell script from a Java program.

If you have a shell script say then you can run it from a Java program using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).

Shell script

echo 'starting script'
mkdir test
cd test
touch SAMPLE

Using Runtime.getRunTime().exec to execute shell script


public class RunningSS {
 public static void main(String[] args) {
  Process p;
  try {
   String[] cmd = { "sh", "/home/adb/Documents/"};
   p = Runtime.getRuntime().exec(cmd); 
   BufferedReader reader=new BufferedReader(new InputStreamReader(
   String line; 
   while((line = reader.readLine()) != null) { 
  } catch (IOException e) {
   // TODO Auto-generated catch block
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block

After executing this Java program with the given shell script, if you verify at the location where your Java program is you will see a directory test created and a file SAMPLE with in that directory.

Wednesday, March 17, 2021

Difference Between ArrayList And LinkedList in Java

In Java collections framework ArrayList and LinkedList are two different implementations of List interface (LinkedList also implement Deque interface though).

In most of the cases we do use ArrayList and it works very well but there are some use cases where using LinkedList may be a better choice. So let's see some of the differences between ArrayList and LinkedList in Java, it will help you in making an informed choice when to use ArrayList and when a LinkedList.

ArrayList Vs LinkedList in Java

1- If we have to list the differences between the LinkedList and ArrayList in Java, first difference is in the implemenation itself-
LinkedList is implemented using a doubly linked list concept where as ArrayList internally uses an array of Objects which can be resized dynamically.

Tuesday, March 16, 2021

TreeSet in Java With Examples

TreeSet in Java is also one of the implementation of the Set interface like HashSet and LinkedHashSet. TreeSet implements the NavigableSet interface and extends the AbstractSet class.

Just like other implementations of the Set interface HashSet and LinkedHashSet, TreeSet also stores unique elements. How TreeSet in Java differs from other Set implementations is that TreeSet stores its elements in sorted order. The elements are ordered using their natural ordering or a comparator can be provided at set creation time to provide custom ordering (We'll see an example a little later).

How TreeSet is implemented in Java

TreeSet in Java uses a tree data structure to store its elements thus providing guaranteed log(n) time cost for the basic operations (add, remove and contains).

As we have seen while discussing HashSet and LinkedHashSet internally these implementations use their map counterparts i.e. HashMap and LinkedHashMap respectively. Same way TreeSet also uses TreeMap internally to store its elements.

Monday, March 15, 2021

Java LinkedBlockingQueue With Examples

LinkedBlockingQueue in Java is an implementation of BlockingQueue interface. It is added in Java 5 along with other concurrent utilities like CyclicBarrier, Phaser, ConcurentHashMap, CopyOnWriteArraySet etc.

LinkedBlockingQueue in Java internally uses linked nodes to store elements. It is optionally bounded and that's where it differs from another implementation of BlockingQueue, ArrayBlockingQueue which is a bounded queue, another difference between the two is how elements are stored internally ArrayBlockingQueue uses array internally whereas LinkedBlockingQueue uses linked nodes. Since LinkedBlockingQueue is optionally bounded so it has both types of constructors

  • one where initial capacity can be passed thus making it bounded.
  • Or
  • without any capacity thus making it unbounded. Note that in case no initial capacity is defined capacity of LinkedBlockingQueue is Integer.MAX_VALUE.

How to Compile Java Program at Runtime

This post talks about how you can compile a java program at runtime. You may have a case where you get a Java file path by reading a property file and you need to compile and run that Java file or you may have a scenario where at run time a program file is created rather than some script which you need to compile and run.

In such cases you need to compile your code at run time from another Java program. It can be done using JavaCompiler interface and ToolProvider class. Note that these classes are provided from Java 6.

Also note that you will need JDK to run it not JRE, so you need to have JDK libraries not JRE. If you are using eclipse and your JRE System library is pointing to JRE path make sure it points to JDK. You can do that by right clicking on your project and going to Java Build Path through properties. There click on Libraries tab and select the JRE System Library which points to jre path and click Edit.

Wednesday, March 10, 2021

Difference Between CountDownLatch And CyclicBarrier in Java

Though both CountDownLatch and CyclicBarrier are used as a synchronization aid that allows one or more threads to wait but there are certain differences between them. Knowing those differences between CountDownLatch and CyclicBarrier in Java will help you to decide when one of these utilities will serve you better and of course it is a good java interview question too.

CountDownLatch Vs CyclicBarrier in Java

  1. One of the most important difference is When you are using a CountDownLatch, you specify the number of calls to the countdown() method when creating a CountDownLatch object. So a CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.
    What this means is you can use CountDownLatch with only a single thread and using countdown() to decrement as and when the specified event occur.

    When you are using CyclicBarrier in Java you specify the number of threads that should call await() method in order to trip the barrier. That means if you have a CyclicBarrier initialized to 3 that means you should have at least 3 threads to call await().

Thursday, March 4, 2021

Matrix Multiplication Java Program

In this post we'll see a Java program to multiply two matrices which also gives you an idea about working with two dimensional arrays.

When you multiply two matrices with each other, you actually do a "dot product" of rows and columns. For example if you are multipying a 3X3 matrix with a 3X2 matrix-

matrix multiplication in Java
Matrix multiplication

The result you get can be explained as follows-

s11 = r11Xp11 + r12Xp21 + r13Xp31
s12 = r11Xp12 + r12Xp22 + r13Xp32
s21 = r21Xp11 + r22Xp21 + r23Xp31
s22 = r21Xp12 + r22Xp22 + r23Xp32
s31 = r31Xp11 + r32Xp21 + r33Xp31
s32 = r31Xp12 + r32Xp22 + r33Xp32

When you are writing a Java program to multiply two matrices-

You need an outer loop that will run as many times as there are rows in the first matrix.
Then you’ll have a second loop that will run as many times as the number of columns in the second matrix.
Then you’ll have a third loop that will run as many times as there are columns in the first matrix.

Also remember these points when multiplying one matrix with another-

  1. The number of columns of the first matrix is equal to the number of rows of the second matrix.
  2. The resultant matrix will have the same number of rows as in the first matrix and same number of columns as in the second matrix.

Matrix multiplication Java program

import java.util.Scanner;

public class MatixMultiplication {

  public static void main(String[] args) {
    int rowM1, colM1;
    int rowM2, colM2;
    Scanner in = new Scanner(;
    System.out.print("Enter Number of Rows and Columns of First Matrix : ");
    rowM1 = in.nextInt();
    colM1 = in.nextInt();
    System.out.print("Enter elements of First Matrix : ");
    int M1[][] = new int[rowM1][colM1];
    for(int i = 0; i < rowM1; i++){
      for(int j = 0; j < colM1; j++){
        M1[i][j] = in.nextInt();
    System.out.println("First Matrix : " );
    for(int i = 0; i < rowM1; i++){
      for(int j = 0; j < colM1; j++){
        System.out.print(" " +M1[i][j]+"\t");
    System.out.print("Enter Number of Rows and Columns of Second Matrix : ");
    rowM2 = in.nextInt();
    colM2 = in.nextInt();
    if(colM1 != rowM2){
      throw new IllegalArgumentException("The number of columns of the first matrix should equal the number of rows of the second matrix.");
    System.out.print("Enter elements of Second Matrix : ");
    int M2[][] = new int[rowM2][colM2];
    for(int i = 0; i < rowM2; i++){
      for(int j = 0; j < colM2; j++){
        M2[i][j] = in.nextInt();
    System.out.println("Second Matrix : " );
    for(int i = 0; i < rowM2; i++){
      for(int j = 0; j < colM2; j++){
        System.out.print(" " +M2[i][j] + "\t");
    //same number of rows as in the first matrix and 
    //same number of columns as in the second matrix
    int resMatrix[][] = new int[rowM1][colM2];
    int sum = 0;
    int row = 0;
    for(int i = 0; i < rowM1; i++){
      for(int j = 0; j < colM2; j++){
        sum = 0;
        for(int k = 0; k < colM1; k++){
          sum = sum + M1[i][k] * M2[k][j];
        resMatrix[i][j] = sum;
    System.out.println("Result Matrix : " );
    for(int i = 0; i < resMatrix.length; i++){
      for(int j = 0; j < colM2; j++){
        System.out.print(" " +resMatrix[i][j]+"\t");


Enter Number of Rows and Columns of First Matrix : 2
Enter elements of First Matrix : 1
First Matrix : 
 1  2  3 
 4  5  6 
Enter Number of Rows and Columns of Second Matrix : 3
Enter elements of Second Matrix : 7
Second Matrix : 
 7   8 
 9   10 
 11  12 
Result Matrix : 
 58   64 
 139  154 

That's all for this topic Matrix Multiplication Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page

Related Topics

  1. Array in Java With Examples
  2. Matrix Subtraction Java Program
  3. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  4. Find Duplicate Elements in an Array Java Program
  5. Check Given Strings Anagram or Not Java Program

You may also like-

  1. How to Display Pyramid Patterns in Java - Part1
  2. How to Convert String to Date in Java
  3. Java Program to Convert a File to Byte Array
  4. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  5. Marker interface in Java
  6. Switch Case Statement in Java With Examples
  7. String in Java Tutorial
  8. Dependency Injection in Spring Framework

Wednesday, March 3, 2021

Check Given Strings Anagram or Not Java Program

Write a Java program to check whether the given strings are anagrams or not is a frequently asked Java interview question. Some other frequently asked Java programs are counting chars in a string and given string is a palindrome or not.

What is anagram

Before going into the Java code for checking whether the given strings are anagaram or not let's first see what exactly is Anagram.

Two strings are called anagram if you can rearrange the letters of one string to produce the second string, using all the letters of the first string only once. While doing that, usually, you don't consider spaces and punctuation marks.

Some Examples- "keep" and "peek", "School Master" and "The Classroom".

Logic for Anagram program

Java program to check whether the given strings are anagrams or not can be written by-

  • Sorting both the strings
  • or
  • By iterating one of the string char by char and making sure that the second string has the same character present

Tuesday, March 2, 2021

Reading File in Java Using Scanner

Though reading file using BufferedReader remains one of the most used way to read a file in Java but there are other ways too like using Scanner class. This post shows how you can read a file in Java using Scanner class.

Scanner is used widely to read input from console as it has a constructor which takes InputStream as argument. But it also has a constructor which takes File as argument and also has methods hasNextLine() and nextLine() to find if there is another line of input and reading the line from input respectively. Using that constructor you can read a file in Java using Scanner.

One other benefit of using Scanner is that it has a useDelimiter() method, using this method file delimiter can be set thus making Scanner a good choice for reading and parsing CSV, tab delimited or pipe symbol separated files in Java.

Monday, March 1, 2021

Association, Aggregation And Composition in Java

When you model a system you can see that most of the classes collaborate with each other in many ways. In object-oriented modelling there are broadly three kind of relationships.

  1. Dependencies
  2. Generalizations
  3. Associations
This post is about association and two types of associations:
  • Aggregation
  • Composition

Many people get confused about these terms so I’ll try to define Association, Aggregation and composition with Java examples, how these terms relate to each other and what are the differences among Association, Aggregation and Composition.