Friday, April 9, 2021

Java SynchronousQueue With Examples

SynchronousQueue which is an implementation of the BlockingQueue interface was added in Java 5 along with other concurrent utilities like ConcurrentHashMap, ReentrantLock, Phaser, CyclicBarrier etc.

How SynchronousQueue differs from other implementations of BlockingQueue like ArrayBlockingQueue and LinkedBlockingQueue is that SynchronousQueue in Java does not have any internal capacity, not even a capacity of one. In SynchronousQueue each insert operation must wait for a corresponding remove operation by another thread, and vice versa.

What that means is, if you put an element in SynchronousQueue using put() method it will wait for another thread to receive it, you can't put any other element in the SynchronousQueue as it is blocked. Same way in case there is thread to remove an element (using take() method) but there is no element in the queue it will block and wait for an element in the queue.

Java SynchronousQueue differs in functionality

Since SynchronousQueue has a very special functionality which differs from other BlockingQueue implementations so methods in Java SynchronusQueue behave a little differently. Actually calling it a Queue itself is a bit of wrong statement as there is never more than one element present. It's more of a point-to-point handoff.

As an example take peek() method, which in other BlockingQueue implementations work as follows-

peek() - Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

Since in SynchronousQueue an element is only present when you try to remove it so peek() method in this class always returns null.

Iterator in SynchronousQueue returns an empty iterator in which hasNext always returns false.

For purposes of other Collection methods a SynchronousQueue acts as an empty collection, so methods like

  • contains- Always returns false. A SynchronousQueue has no internal capacity.
  • remove- Always returns false. A SynchronousQueue has no internal capacity.
  • isEmpty()- Always returns true. A SynchronousQueue has no internal capacity.

Thursday, April 8, 2021

Lock Striping in Java Concurrency

If you have only one lock for the whole data structure like Array or Map and you are synchronizing it and using it in a multi-threaded environment, then effectively any given time only one thread can manipulate the map, as there is only a single lock. All the other threads would be waiting to get the monitor.

If you have to visualize a HashTable or a synchronized HashMap it can be depicted like the following image.

If there are 6 threads only one can get the lock and enter the synchronized collection. Even if the keys these threads want to get (or manipulate the values) are in different buckets as in the image if two threads want to access keys in bucket 0, two threads want to access keys in bucket 1 and two threads want to access keys in bucket n-3, any given time only one thread will get access.

Single lock for whole collection
Single lock for the whole collection

Wednesday, April 7, 2021

Angular HttpClient + Spring Boot REST API CRUD Backend Service

In this tutorial we’ll see how to communicate with a back end service using the Angular HttpClient. As an example we’ll take a Spring Boot REST API crud application as a back end service and connect to it from an Angular front end application using the Angular HttpClient.

In this post stress is more on explaining how to use Angular client HTTP API, how to make a request to back end service and how to catch errors.

Back end Spring Boot service

In the Spring Boot application we have a Rest Controller class with handler mappings for different CRUD operations. DB used is MySQL and the DB table is User.

To get more details and code for the Spring Boot CRUD application, refer this post- Spring Boot REST API CRUD Example With Spring Data JPA

Only change that is required in the Spring boot application is to add @CrossOrigin annotation in the Controller class to enable cross-origin resource sharing (CORS). If you won't use this annotation cross browser HTTP request won't be allowed and the Spring Boot application won't accept any request coming from http://localhost:4200

Tuesday, April 6, 2021

Print Odd-Even Numbers Using Threads And wait-notify Java Program

In this post we'll see a Java program to print odd and even numbers sequentially using two threads. One thread generates odd numbers and another even numbers. This Java program makes use of inter-thread communication using wait, notify, notifyAll to print odd-even numbers.

Java program to print odd-even numbers using threads

There is a class SharedPrinter whose object is shared between two threads. In this class there is a method printEvenNum() for printing even numbers and method printOddNum() for printing odd numbers.

These two methods are called by the respective threads EvenNumProducer and OddNumProducer and these threads communicate using wait and notify, of course from inside a synchronized block.

public class EvenOddThreadDemo {
  public static void main(String[] args) {
    // shared class object
    SharedPrinter sp = new SharedPrinter();
    // creating two threads
    Thread t1 = new Thread(new EvenNumProducer(sp, 10));
    Thread t2 = new Thread(new OddNumProducer(sp, 10));
    // starting threads
    t1.start();
    t2.start();
  }
}
// Shared class used by both threads
class SharedPrinter{
  boolean evenFlag = false;
 
  //Method for printing even numbers
  public void printEvenNum(int num){
    synchronized (this) {
      // While condition as mandated to avoid spurious wakeup
      while(!evenFlag){
        try {
          //asking current thread to give up lock
          wait();
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      System.out.println(num);
      evenFlag = false;
      // Wake up thread waiting on this monitor(lock)
      notify();
    }
  }
 
  //Method for printing odd numbers
  public void printOddNum(int num){
    synchronized (this) {
      // While condition as mandated to avoid spurious wakeup
      while(evenFlag){
        try {
         //asking current thread to give up lock
         wait();
        } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }
      }
      System.out.println(num);
      evenFlag = true;
      // Wake up thread waiting on this monitor(lock)
      notify();   
    }
  }
}

// Thread Class generating Even numbers
class EvenNumProducer implements Runnable{
  SharedPrinter sp;
  int index;
  EvenNumProducer(SharedPrinter sp, int index){
    this.sp = sp;
    this.index = index;
  }
  @Override
  public void run() {
    for(int i = 2; i <= index; i = i+2){
      sp.printEvenNum(i);
    }   
  }   
}

//Thread Class generating Odd numbers
class OddNumProducer implements Runnable{
  SharedPrinter sp;
  int index;
  OddNumProducer(SharedPrinter sp, int index){
    this.sp = sp;
    this.index = index;
  }
  @Override
  public void run() {
    for(int i = 1; i <= index; i = i+2){
      sp.printOddNum(i);
    }
  }
}

Output

1
2
3
4
5
6
7
8
9
10

That's all for this topic Print Odd-Even Numbers Using Threads And wait-notify 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. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  2. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  3. How to Run Threads in Sequence in Java
  4. How to Create Deadlock in Java
  5. Producer-Consumer Java Program Using volatile

You may also like-

  1. Java Program to Create Your Own BlockingQueue
  2. Java Program to Get All DB Schemas
  3. Count Number of Words in a String Java Program
  4. How to Convert Date And Time Between Different Time-Zones in Java
  5. Marker interface in Java
  6. Synchronization in Java - Synchronized Method And Block
  7. Method Reference in Java
  8. Spring Java Configuration Example Using @Configurations

Monday, April 5, 2021

Print Odd-Even Numbers Using Threads And Semaphore Java Program

This Java program prints odd and even numbers alternatively using two threads. One thread prints odd numbers and another thread even numbers. This program makes use of inter-thread communication using Semaphore class which is present in concurrent util package.

The Semaphore class present in java.util.concurrent package is a counting semaphore in which a semaphore, conceptually, maintains a set of permits. Semaphore class has two methods that make use of permits-

  • acquire()- Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted. It has another overloaded version acquire(int permits).
  • release()- Releases a permit, returning it to the semaphore. It has another overloaded method release(int permits).

Java Program to print odd-even numbers using threads and semaphore

In the Java program there is class SharedPrinter whose object is shared between two threads. In this class there is a method printEvenNum() for printing even numbers and method printOddNum() for printing odd numbers.

These two methods are called by the respective threads EvenNumProducer and OddNumProducer and these threads communicate using semaphore. Idea is to have 2 semaphores when first is acquired release second, when second is acquired release first. That way shared resource has controlled access and there is inter-thread communication between the threads.

Note that one of the semaphore semEven is initialized with 0 permits that will make sure that even number generating thread doesn't start first.

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

public class EvenOddSem {

 public static void main(String[] args) {
    SharedPrinter sp = new SharedPrinter();
    // Starting two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new EvenNumProducer(sp, 10));
    executor.execute(new OddNumProducer(sp, 10));
    executor.shutdown();
 }
}

//Shared class used by both threads
class SharedPrinter{
 boolean evenFlag = false;
 // 2 semaphores 
 Semaphore semEven = new Semaphore(0);
 Semaphore semOdd = new Semaphore(1);
 
 //Method for printing even numbers
 public void printEvenNum(int num){
  try {
   semEven.acquire();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(num);
  semOdd.release(); 
 }
 
 //Method for printing odd numbers
 public void printOddNum(int num){
  try {
   semOdd.acquire();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(num);
  semEven.release();
   
 }
}

//Thread Class generating Even numbers
class EvenNumProducer implements Runnable{
  SharedPrinter sp;
  int index;
  EvenNumProducer(SharedPrinter sp, int index){
    this.sp = sp;
    this.index = index;
  }
  @Override
  public void run() {
    for(int i = 2; i <= index; i = i+2){
      sp.printEvenNum(i);
    }   
  }  
}

//Thread Class generating Odd numbers
class OddNumProducer implements Runnable{
  SharedPrinter sp;
  int index;
  OddNumProducer(SharedPrinter sp, int index){
    this.sp = sp;
    this.index = index;
  }
  @Override
  public void run() {
    for(int i = 1; i <= index; i = i+2){
      sp.printOddNum(i);
    }
  }
} 

Output

1
2
3
4
5
6
7
8
9
10

That's all for this topic Print Odd-Even Numbers Using Threads And Semaphore 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. How to Run Threads in Sequence in Java
  2. How to Create Deadlock in Java
  3. Setting And Getting Thread Name And Thread ID in Java
  4. Java Program to Create Your Own BlockingQueue
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. Convert float to String in Java
  2. How to Read Input From Console in Java
  3. Synchronization in Java - Synchronized Method And Block
  4. Race Condition in Java Multi-Threading
  5. Java ReentrantLock With Examples
  6. Lambda Expressions in Java 8
  7. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  8. Autowiring in Spring Using @Autowired and @Inject Annotations

Saturday, April 3, 2021

Difference Between Comparable and Comparator in Java

While sorting elements in collection classes, these two interfaces Comparable and Comparator in Java come into picture. Both of these interfaces are used to sort collection elements. An obvious question which comes to mind is why two different interfaces?

In this post we'll see the difference between Comparable and Comparator interfaces in Java and why both of them are required. Before going into the differences between these two, let's have a brief introduction of both.


Comparable interface in Java

Comparable interface is defined as follows-

public interface Comparable<T> {
 public int compareTo(T o);
}

Classes implementing this interface need to provide sorting logic in compareTo() method.

The ordering imposed by the implementation of this interface is referred to as the class' natural ordering, and the implemented compareTo method is referred to as its natural comparison method.
Classes implementing this interface can be sorted automatically by Collections.sort (and Arrays.sort) method. Objects that implement this interface can be used as keys in a sorted map (like TreeMap) or as elements in a sorted set (like TreeSet) without the need to specify a comparator.

Friday, April 2, 2021

try-catch Block in Java Exception Handling

In this post we'll see how exception handling can be done using try-catch block in Java.

try block in Java

try block is used to enclose the code that might throw an exception. try block must be followed by either catch or finally block or both.

General form of Java try block

try {
  code 
}
catch and/or finally blocks
 

catch Block in Java

catch block is used to handle the exception thrown with in a try block. There can't be any code between the end of the try block and the beginning of the first catch block.