Saturday, February 29, 2020

What is difference between wait and sleep in Java Thread?

Oracle Java Thread, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Prep, Core Java


Wait vs sleep in Java


Differences between wait and sleep method in Java multi-threading is one of the very old questions asked in Java interviews. Though both wait and sleep put thread on waiting state, they are completely different in terms of behavior and use cases. Thread.sleep(long millis) is meant for introducing pause, releasing CPU and giving another thread an opportunity to execute while wait is used for inter thread communication in Java. These methods are defined in java.lang.Object class and available to every object in Java. It is based upon object lock, if you remember every object in Java has implicit lock, also known as monitor. When a thread enter into a synchronized method it acquired the lock which is used to protect the critical reason e.g. it acquired lock on current object if it is going inside an instance synchronized method and lock object on class literal if its entering into a static synchronized method. By using wait() and notify() method two threads can communicate with each other which is key to solve many concurrency problems e.g. produce consumer problem, dining philosopher problem, reader and writer problem, and to implement several Concurrency designs.

In this tutorial, you will learn about following this about wait() and sleep() method in Java :

What is wait() method in Java?
What is sleep() method in Java?
What is difference between wait and sleep in Java?
Where to use wait and sleep in Java?

What is wait and sleep method in Java


Wait method is defined in Object class and it available to all object, wait() method is always discussed along with its counterpart notify() and notifyAll() method and used in inter thread communication in Java.

The wait() method puts a thread on wait by checking some condition like in Producer Consumer problem, producer thread should wait if Queue is full or Consumer thread should wait if Queue is empty.

The notify() method is used to wake up waiting thread by communicating that waiting condition is over now for example once producer thread puts an item on empty queue it can notify Consumer thread that Queue is not empty any more. On the other hand Sleep() method is used to introduce pause on Java application.

You can put a Thread on sleep, where it does not do anything and relinquish the CPU for specified duration. When a Thread goes to Sleep it can be either wake up normally after sleep duration elapsed or it can be woken up abnormally by interrupting it.

Difference between Wait and Sleep method in Java Thread


In last section we saw what is wait and sleep method and in this section we will see what are differences between wait and sleep method in Java. As I told before apart from waiting they are completely different to each other:

Oracle Java Thread, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Prep, Core Java
1) First and most important difference between Wait and sleep method is that wait method must be called from synchronized context i.e. from synchronized method or block in Java. If you call wait method without synchronization, it will throw IllegalMonitorStateException in Java. On the other hand there is no requirement of synchronization for calling sleep method , you can call it normally.

2) Second worth noting difference between wait and sleep method is that, wait operates on Object and defined in Object class while sleep operates on current Thread and defined in java.lang.Thread class.

3) Third and another significant difference between wait and sleep in Java is that, wait() method releases the lock of object on which it has called, it does release other locks if it holds any while sleep method of Thread class does not release any lock at all.

4) wait method needs to be called from a loop in order to deal with false alarm i.e. waking even though waiting condition still holds true, while there is no such thing for sleep method in Java. its better not to call Sleep method from loop.

here is code snippet for calling wait and sleep method in Java

synchronized(monitor)
while(condition == true){ monitor.wait())  //releases monitor lock

Thread.sleep(100); //puts current thread on Sleep

5) One more difference between wait and sleep method which is not as significant as previous ones is that wait() is a non static method while sleep() is static method in Java.

Oracle Java Thread, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Prep, Core Java

Where to use wait and sleep method in Java


By reading properties and behavior of wait and sleep method it's clear that wait() method should be used in conjunction with notify() or notifyAll() method and intended for communication between two threads in Java while Thread.sleep() method is a utility method to introduce short pauses during program or thread execution. Given the requirement of synchronization for wait, it should not be used just to introduce pause or sleep in Java.

In summary wait and sleep method are completely different to each other and have different use cases. Use wait() and notify() method for inter thread communication while use sleep() method for introducing small pause during thread execution. Also remember, that wait() method will release the lock acquired when it entered into synchronized block or method, but sleep() method will keep the lock with itself. So if you design require releasing the lock during wait period then use wait() and notify method otherwise just use sleep().

Thursday, February 27, 2020

Database Transaction Tutorial in SQL with Example for Beginners

Oracle Java Study Materials, Oracle Java Tutorial and Materials, Oracle Java Guides, Oracle Java Certifications

A database transaction is an important concept to understand while working in database and SQL. Transaction in the database is required to protect data and keep it consistent when multiple users access the database at the same time.  In this database transaction preparation we will learn what is a transaction in a database, why do you need transaction in the database, ACID properties of database transaction and an example of database transaction along with commit and rollback.   Almost all vendors like Oracle, MySQL, SQL Server or Sybase provide transaction facility but MySQL only provide it for certain storage engines like InnoDB and BDB and not for MyISAM.

What is transaction in database?


Database transaction is a collection of SQL queries which forms a logical one task. For a transaction to be completed successfully all SQL queries have to run successfully. Database transaction executes either all or none, so for example if your database transaction contains 4 SQL queries and one of them fails then change made by other 3 queries will be rolled back. This way your database always remain consistent whether transaction succeeded or failed. The transaction is implemented in the database using SQL keyword transaction, commit, and rollback. Commit writes the changes made by transaction into database and rollback removes temporary changes logged in transaction log by database transaction.

Database Transaction


Why transaction is required in database

The database is used to store data required by real life application e.g. Banking, Healthcare, Finance etc. All your money stored in banks is stored in the database, all your shares of DMAT account is stored in the database and many application constantly works on these data. In order to protect data and keep it consistent, any changes in this data need to be done in a transaction so that even in the case of failure data remain in the previous state before the start of a transaction. Consider a Classical example of ATM (Automated Tailor Machine); we all use to withdraw and transfer money by using ATM. If you break withdrawal operation into individual steps you will find:

1) Verify account details.
2) Accept withdrawal request
3) Check balance
4) Update balance
4) Dispense money

Suppose your account balance is 1000$ and you make a withdrawal request of 900$. At fourth step, your balance is updated to 900$ and ATM machine stops working due to power outage
Once power comes back and you again tried to withdraw money you surprised by seeing your balance just 100$ instead of 1000$. This is not acceptable by any person in the world :) so we need a transaction to perform such task. If SQL statements would have been executed inside a transaction in database balance would be either 100$ until money has been dispensed or 1000$ if money has not been dispensed.

ACID Properties of database transaction

There are four important properties of database transactions these are represented by acronym ACID and also called ACID properties or database transaction where:

A stands for Atomicity, Atom is considered to be smallest particle which can not be broken into further pieces.database transaction has to be atomic means either all steps of transaction completes or none of them.

C stands for Consistency, transaction must leave database in consistent state even if it succeed or rollback.

I is for Isolation

Two database transactions happening at same time should not affect each other and has consistent view of database. This is achieved by using isolation levels in database.

D stands for Durability

Data has to be persisted successfully in database once transaction completed successfully and it has to be saved from power outage or other threats. This is achieved by saving data related to transaction in more than one places along with database.

When to use database transaction

Whenever any operation falls under ACID criteria you should use transactions. Many real world scenarios require transaction mostly in banking, finance and trading domain.

How to implement transaction in SQL

Database transaction is implemented in SQL using three keywords start transaction, commit and rollback.once you type start transaction, database starts a transaction and execute all subsequent SQL statements in transaction and keep track of all of them to either commit or rollback changes. Commit keywords saves then changes made by transaction into database and after commit change is normally visible to other transaction though is subject to isolation level. In case you encountered any error while executing individual sql statements inside database transaction, you can rollback all your changes by executing "rollback" command.

Database Transaction Example


To understand database transaction better let's see a real life example of transaction in database. For this example we will assume we have an Account table which represent a Bank Account and we will transfer money from one account to another account

Request: transfer 900$ from Account 9001 to 9002

start transaction
select balance from Account where Account_Number='9001';
select balance from Account where Account_Number='9002';
update Account set balance=balance-900 here Account_Number='9001' ;
update Account set balance=balance+900 here Account_Number='9002' ;
commit; //if all sql queries succed
rollback; //if any of Sql queries failed or error

Database transaction in MySQL


I have talked aobut different databse storage engines available in mysql e.g. myISAM or InnoDB. Not all mysql engines supports transaction in order to make transaction works in mysql you either need to use InnoDB or BDB Engine. You can specify engige while creating table in mysql or you can also change your engine in mysql by using ALTER keyword. For example "ALTER TABLE tablename TYPE=InnoDB;

Important point about database transaction


1. Database transaction is nothing but a set of SQL statement.

2. Transaction in database is either all or none means either all SQL statement success or none.

3. Its good practice to execute sql query inside transaction and commit or rollback based on result but you need to be little careful with transaction log. To faciliate rollback and commit every sql query which executed inside database transaction is written into transaction log and size of transaction log can grow significantly if don't commit or rollback for longtime.

4. Effect of two simultaneous database transaction into data is controlled by using Isolation level. Isolation level is used to separate one database transaction with other and currently there are four database isolation levels:

1) Read Uncommitted
This is the lowest level of database isolation level in this one database transaction can see changes made by other database transaction which is not yet committed. This can allow you dirty read so quite dangerous.
2) Read Committed
This is slightly better where one database transaction only sees committed changes by other database transaction. But this is also not safe and can lead you to non-repeatable reads problem.
3) Repeatable Reads
4) Serializable

The highest level of database isolation level. In this, all database transactions are totally isolated with other database transaction.though this is safe but this safety can cause a significant performance hit.

5. MyISAM storage engine in MySQL doesn't support transaction. In order to make transaction works in MySQL use InnoDB.

6. Databse transaction should follow ACID properties.

That’s all for now on database transaction tutorial, I will add more useful points about transaction in databse as I come across or recall, you can also provide your input and issues face during transaction in database on different RDBMS e.g. Oracle, MySQL, MSSQL Server or Sybase etc.

Wednesday, February 26, 2020

Difference between save vs persist and saveOrUpdate in Hibernate

Save vs. saveOrUpdate vs. persist in Hibernate


Hibernate Session class provides a couple of ways to save an object into the database by methods like save, saveOrUpdate, and persist.  You can use either save(),  saveOrUpdate() or persist() based upon your requirement for persisting objects into the database. The key thing is that all these objects are used to store data into the database but they also make a transient object persistent in Hibernate.

Along with Spring framework Interview questions, Hibernate questions are also quite popular on Java interviews because of its status as leading ORM. It's good to prepare some questions from Hibernate before appearing in any J2EE interviews.

Difference between save and saveOrUpdate in Hibernate


The main difference between save and saveOrUpdate method is that save() generates a new identifier and INSERT record into the database while saveOrUpdate can either INSERT or UPDATE based upon the existence of a record. Clearly, saveOrUpdate is more flexible in terms of use but it involves extra processing to find out whether a record already exists in the table or not.

In summary, the save() method saves records into the database by INSERT SQL query, Generates a new identifier, and returns the Serializable identifier back.

On the other hand  saveOrUpdate() method either INSERT or UPDATE based upon the existence of an object in the database. If a persistence object already exists in the database then UPDATE SQL will execute, and if there is no corresponding object in the database, then INSERT will run.

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Prep, Oracle Java Exam Prep

Difference between save and persist method in Hibernate


In the last section, we saw What are the difference between save and saveOrUpdate, and now we will see the difference in save vs. persist method.

1)The first difference between save and persist is there return type. Similar to save method, persist also INSERT records into the database, but return type of persist is void while return type of save is Serializable Object. 

2) Another difference between persist and save is that both methods make a transient instance persistent. However, persist() method doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.

This diagram also explains the life-cycle of a persistence object in Hibernate and how it moves from one state to another like Transient to Persistent to Detached. You can see that both save() and saveOrUpdate() method move an object from Transient to Persistent state.

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Prep, Oracle Java Exam Prep

3) One more thing which differentiates persist and save method in Hibernate is that it is their behavior on the outside of transaction boundaries. persist() method guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. save() method does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (like "identity" generator), this INSERT happens immediately, no matter if you are inside or outside of a transaction.

4) The fourth difference between save and persist method in Hibernate is related to previous differences in save vs. persist. Because of its above behavior of persist method outside transaction boundary, it's useful in long-running conversations with an extended Session context. On the other hand, the save method is not good in a long-running conversation with an extended Session context.

These were some differences between save, saveOrUpdate, and persist method of Hibernate. All three methods are related to saving Objects into a database, but their behavior is quite different. Knowledge of save, persist and saveOrUpdate not only helps to decide better use of Hibernate API but also help you to do well in Hibernate interviews.

Tuesday, February 25, 2020

How to Implement Thread in Java with Example

How to implement Thread in Java


In my opinion, Thread is one of the most important features of Java programming language which helped it to become the most popular programming language. I remember, when I first started learning Java in one of the programming class in India how important Thread was portrait and how much emphasis given on clear understanding of multi-threading. It’s still popular and one of most sought after skill in Java programmer because writing concurrent and multi-threaded application in Java is challenging, despite Java providing excellent support at language level using synchronized and volatile keyword. Main problem with using multiple threads and writing multi-threaded code is issues related to concurrency e.g. deadlock, livelock, race conditions etc, It takes lot of effort to implement multi-threading correctly in Java application.

In this core Java tutorial I will share my experience on different way of implementing Thread in Java;  By the way difference between Thread and Runnable in Java is also a very common core Java interview question and asked mostly during junior level Java interview.

After reading this tutorial, you will not only able to create and start thread but also able to answer what is difference in two ways of implementing thread in Java, by implementing Runnable interface or by extending Thread class.

How to make Thread in Java


There are two ways of implementing threading in Java

1) By extending java.lang.Thread class, or

2) By implementing java.lang.Runnable interface.

Before we go into implementation details I just like to cover when we use Thread in Java?  So we use thread if we want some part of code is executed parallel and we put that code inside run() method of either Thread class or Runnable interface.

Actually public void run() method is defined in Runnable interface and since java.lang.Thread class implements Runnable interface it gets this method automatically. I remember by first Java multi threading example which was an animation program where multiple threads were used in Applet to create animation of words falling from top left, middle and top right of the page. That was pretty exciting at that time because till then I only know program which takes input from command prompt and print output on command prompt.

Java Thread Tutorial and Example


So now the interview question  which way of implementing Thread is better? Extending Thread class or implementing Runnable method?

In my opinion implementing Runnable is better because in Java we can only extend one class so if we extend Thread class we can not extend any other class while by implementing Runnable interface we still have that option open with us.

Second reason which make sense to me is more on OOPS concept according to OOPS if we extend a class we provide some new feature or functionality , So if the purpose is just to use the run() method to define code its better to use Runnable interface. If you are still not convince on why implementing Runnable is better than extending Thread class for creating threads in Java.


So first step is complete, you have implemented thread by now. Next step is to actually create object of thread class and start it. This is will create a separate path of execution parallel to main thread. Java thread is state based so it remains in predefined state at any given time and state transition occurs by calling different thread method. So, when you create object of your class which has implemented Runnable or extended Thread, you just create an object of Thread class, Thread will not start until you call the start() method of java.lang.Thread class. This is shown clearly in above thread state transition diagram in Java. It is now in NEW state, when we call start() method Java Virtual machine execute run() method of that Thread class it goes into RUNNBLE state. Now, it's upto thread scheduler to assign CPU to this thread. From here on it can either complete its execution and go to TERMINATED state or can go into WAITING, TIMED WAITING and BLOCKED state. By the way if you notice, when we call start() method, it eventually calls run() method, can anybody guess what will happen if we call the run() method directly instead of calling start() method ?

That another popular multi-threading interview question and answer is simple there would be no Error or Exception run() method will simply be executed in the same Thread and new Thread will not be created. Another follow up question would be what will happen if you call start() method twice in same Thread object e.g.

mythread.start(); 
mythread.start(); //this line will throw IllegalThreadStateException

//implementing Thread by extending Thread class
 public class MyThread extends Thread{       

   public void run(){
      System.out.println(" Thread Running " + Thread.currentThread().getName());
   }
 }

//implementing Thread by implementing Runnable interface

public class MyRunnable implements Runnable{         

    public void run(){
       System.out.println(" Create Thread " + Thread.currentThread().getName());
    }

 }

//starting Thread in Java
Thread mythread = new MyThread(); //Thread created not started
mythread.setName("T1");
Thread myrunnable = new Thread(new MyRunnable(),"T2"); //Thread created       

mythread.start(); //Thread started now but not running 
myrunnable.start();

Bonus Tip


TIP1: It’s not guaranteed that thread mythread will start before thread myrunnable it depends upon Thread scheduler.

TIP2: Thread will be said to go on dead state once execution of run() method finished and you can not start that thread again.

Monday, February 24, 2020

How to Convert Date to String in Java with Example

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Exam Prep, Oracle Java Prep

Some times we need to convert java.util.Date to string in java  may for displaying purpose I need it that while working on displaytag then I thought about this article  to list down various way of converting this in various ways, after some reading I found that SimpleDateFormat makes this quite easy. To get the feel of Date API in java and to familiarize ourselves with these classes we will see different examples of converting date to String in our application. Both DateFormat and SimpleDateFormat class belongs java.text package and they are very powerful and you can use them for conversion. it also good for parsing string into date and can be used to show in various locale also.

Steps for converting Date to String in Java


Its very easy with the use of SimpleDateFormat, here are the exact steps:

1) First step is to create a date format using SimpleDateFormat class

2) Call format() method of SimpleDateFormat by passing Date object this will return String representation of date into specified date format.

Now let’s see few examples of converting date to String in java:

//Creating Date in java with today's date.
Date dateNow = new Date();

//change date into string yyyyMMdd format example "20110914"
SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("yyyyMMdd");
String date_to_string = dateformatyyyyMMdd.format(dateNow);
System.out.println("date into yyyyMMdd format: " + date_to_string);

//converting  date into ddMMyyyy format example "14092011"
SimpleDateFormat dateformatddMMyyyy = new SimpleDateFormat("ddMMyyyy");
date_to_string = dateformatddMMyyyy.format(dateNow);
System.out.println("Today's date into ddMMyyyy format: " + date_to_string);

//change date to string on dd-MM-yyyy format e.g. "14-09-2011"
SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
date_to_string = dateformatJava.format(dateNow);
System.out.println("Today's date into dd-MM-yyyy format: " + date_to_string);

//converting date to string dd/MM/yyyy format for example "14/09/2011"
SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy");
date_to_string = formatDateJava.format(dateNow);
System.out.println("Today's date into dd/MM/yyyy format: " + date_to_string);

//date to dd-MMM-yy format e.g. "14-Sep-11"
SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd-MMM-yy");
date_to_string = ddMMMyyFormat.format(dateNow);
System.out.println("Today's date into dd-MMM-yy format: " + date_to_string);

//convert date to dd-MMMM-yy format e.g. "14-September-11"
SimpleDateFormat ddMMMMyyFormat = new SimpleDateFormat("dd-MMMM-yy");
date_to_string = ddMMMMyyFormat.format(dateNow);
System.out.println("date into dd-MMMM-yy format: " + date_to_string);

For complete details on available symbols for date conversion you can check java doc of DateFormat and SimpleDateFormat class.  Here are some important points about SimpleDateFormat which is worth remembering

1) Common point of confusion between “m” and “M” , small case “m” represent minutes while “M” represent Month Also “d” represent date in month while “D” represent Day of week. This is most common cause of error while converting String to date and back date to string. In shot ddMMyy is not equal to DDmmyy.

2) It’s also worth noting that SimpleDateFormat  are not thread-safe. They are not synchronized so its better you create separate DateFormat for each thread to avoid any race condition while parsing date in java.

It’s very important for any java developer be it senior or junior to get familiarize himself with Date, Time and Calendar API. SimpleDateFormat is an excellent utility for converting String to Date and then Date to String but you just need to be little careful with format and thread-safety.

Friday, February 21, 2020

How to Stop Thread in Java Code Example

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Prep

The thread is one of important Class in Java and multithreading is most widely used a feature,but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default, a Thread stops when execution of run() method finish either normally or due to any Exception.In this article, we will How to Stop Thread in Java by using a boolean State variable or flag. Using a flag to stop Thread is a very popular way  of stopping the thread and it's also safe because it doesn't do anything special rather than helping run() method to finish itself.

Also Read: Oracle Java Tutorials

How to Stop Thread in Java


As I said earlier Thread in Java will stop once run() method finished. Another important point is that you can not restart a Thread which run() method has finished already , you will get an IllegalStateExceptio, here is a Sample Code for Stopping Thread in Java.

Sample Code to Stop Thread in Java

    private class Runner extends Thread{
    boolean bExit = false;
 
    public void exit(boolean bExit){
        this.bExit = bExit;
    }
 
    @Override
    public void run(){
        while(!bExit){
            System.out.println("Thread is running");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(ThreadTester.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
    }
}

Should we make bExit Volatile

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Prep
How to Stop Thread in Java Tutorial ExampleSince every Thread has its own local memory in Java its good practice to make bExit volatile because we may alter the value of bExit from any thread and make it volatile guarantees that Runner will also see any update done before making bExit.

That’s all on how to stop the thread in Java , let me know if you find any other way of stopping threads in Java without using deprecated stop() method.

Thursday, February 20, 2020

Difference between wait() and join method in Java thread

Though both wait() and join() methods are used to pause the current thread and have a lot of similarities they have different purposes. One of the most obvious differences between the wait() and join() method is that former is declared in java.lang.Object class while join() is declared in java.lang.Thread class. This means that wait() is related to the monitor lock which is held by each instance of an object and join method is related to Thread itself. The wait() method is used in conjunction with notify() and notifyAll() method for inter-thread communication, but join() is used in Java multi-threading to wait until one thread finishes its execution.

 Another difference between wait() and join() method is that former must be called from synchronized method or block but later can be called without a synchronized block in Java.

A good knowledge of differnet thread related methods e.g. start and run, wait and notify, join and yield goes a long way in writing robuts and correct multi-threaded, concurrent Java applications. If you don't know how to use join method, you miss out on writing program where one thread needs to wait for the completion of other thread before it starts.

These were some fundamental difference between wait() and join() method, let's see a couple of more differences and similarities in detail.

Similarities between wait() and join()


Before looking at the difference between wait() and join() method of thread class, let's see some of the key similarities between them:

1) Both wait() and join() is used to pause the current thread in Java. In the first case, the thread which calls the wait() method goes into waiting for the state while in the second case the thread which calls the join() method goes into waiting for the state until the thread on which join has been called finishes its execution.

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Prep, Oracle Java Exam Prep

2) Both wait() and join() are overloaded in Java. You can find a version of both the wait() and join() which accepts a timeout parameter.

3) Both wait() and join() can be interrupted by calling interrupt() method in Java. Which means you can handle the interrupt by catching InterrruptedException in Java.

4) Both wait() and join() are a non-static method and cannot be called from the static context.

Difference between wait() and join() method of thread


So far you have learned what is wait() and join() method, why they are used and some similarities between them. Now is the time to revise and find out some key differences between them.

1) First and foremost difference between wait() and join() method is that wait() is declared and defined in Object class while join() is defined in the thread class.

2) Second important difference between wait() and join() is that wait() must be called from synchronized context i.e. synchronized method or block otherwise it will throw IllegalMonitorStateException but there is no such requirement for calling the join() method in Java.

On the other hand, you can call join() method with and without synchronized context in Java.

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Prep, Oracle Java Exam Prep

3) The third difference between wait() and join() method is that the thread calls wait for () method it releases any lock held for the object on which wait() is called, but calling join() method doesn't release any monitor or lock.

4) Another difference between them is that wait() is used for inter-thread communication while the join() is used for adding sequencing between multiple threads e.g. one thread starts execution after first thread finishes its execution.

5) You can awake a thread waiting by calling wait() method of the object class by using notify() and notifyAll() method but you can not break the waiting imposed by join without interruption or unless the thread on which join is called has finished execution.

That's all about the difference between wait() and join() method in Java. Use wait() when you want inter-thread communication e.g. to solve the producer-consumer problem while using the Thread.join()  method when you want one thread to start execution only if the first thread finishes its execution.

Wednesday, February 19, 2020

How to combine two Map in Java? Example

You can combine two maps in Java by using the putAll() method of java.util.Map interface. This method copies all the mappings from one Map to another, like, if you call it like first.putAll(second), then all mappings from the second Map will be copied into the first Map. Which means if the first map contains 5 elements and the second map contains 10 elements or mapping, then the combined map will contain 15 or fewer mappings. In the case of duplicate keys, the value is overridden or updated from the second map. For example, if the first map has a mapping 1 -> One and second map has mapping 1 -> ONE then after combining the second map into the first one, the value of 1 will be ONE, i.e. the value from the second map.

The putAll() method copies all of the mappings from the specified map to this map. The effect of this call is similar to iterating over the map and calling put(k, v) on this Map once for each mapping from key k to value v in the specified map.

Btw, this is an optional operation for any Map implementation, but HashMap implements this method. You will get the UnsupportedOperationException if the putAll operation is not supported by this map.

The putAll() method also throws NullPointerException if the specified map is null, or if this map does not permit null keys or values, and the specified map contains null keys or values.

It can also throw ClassCastException if the class of a key or value in the specified map prevents it from being stored in this map. Also, the behavior of this operation is undefined if the specified map is modified while the operation is in progress.

Java Program to Copy Values from One Map to Other


Here is a simple program to copy values from one map to other in Java. This way, you can combine mappings, like both keys and values. For example, if you receive two maps of orders from different systems, you can combine them to calculate the total notional value.

In our case, we just have two maps where numbers are mapped to their String values. In one map we have mapped number to equivalent string written in a small case and other maps we have done the same thing, but strings are in capital order.

This has been done to show that in the case of duplicate keys, the values are updated from the second map. This is the basic property of Map and all the Map implementations like HashMap, ConcurrentHashMap, and Hashtable follows it.

Oracle Java Study Material, Oracle Java Prep, Oracle Java Exam Prep, Oracle Java Certification

Java program to combine two maps in Java


import java.util.HashMap;
import java.util.Map;

public class Helloworld {

  public static void main(String[] args) {

    // first map integer to string
    Map<Integer, String> intToString = new HashMap<Integer, String>();
    intToString.put(1, "One");
    intToString.put(2, "Two");
    intToString.put(3, "Three");
    intToString.put(4, "Four");
    intToString.put(5, "Five");

    System.out.println("first map: " + intToString);

    // second map - prime numbers
    Map<Integer, String> primes = new HashMap<>();
    primes.put(2, "TWO");
    primes.put(3, "THREE");
    primes.put(5, "FIVE");
    primes.put(7, "SEVEN");
    primes.put(11, "ELEVEN");

    System.out.println("second map: " + primes);

    // when you combine map, it would contains mapping
    // from the two maps, but for duplicate keys
    // values will be updated from the second map
    // you can choose any map to source and destination
    // for example, in below code, intToString map
    // will contain combined value but primes will
    // not be changed.

    intToString.putAll(primes);

    System.out.println("combined map: " + intToString);
  }

}

Output :

first map: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
second map: {2=TWO, 3=THREE, 5=FIVE, 7=SEVEN, 11=ELEVEN}
combined map: {1=One, 2=TWO, 3=THREE, 4=Four, 5=FIVE, 7=SEVEN, 11=ELEVEN}

Oracle Java Study Material, Oracle Java Prep, Oracle Java Exam Prep, Oracle Java Certification
You can see from the output that in the combined map the value of 2, 3, and 5 is now capital TWO, THREE, and FIVE. Which means their values are updated from the second map. The combined Map also contains new mappings from the second map, like 7 and 11.

That's all about how to combine two maps in Java. It's actually very easy, you just need to remember about putAll() method of java.util.Map class. Though be careful, as I said, if your map, in which you are copying mappings has duplicate keys, then their values will be overwritten by values form the second map.

The putAll() is also an optional operation which means you cannot rely on every single map supporting this operation, but for most purpose, unless you are using HashMap or other Map implementation from JDK, it doesn't matter.

Tuesday, February 18, 2020

10 Examples of ConcurrentHashMap in Java

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Prep, Oracle Java Exam Prep

Hello Java programmers, you might have heard about the ConcurrentHashMap class of java.util.concurrent package. If you don't let me tell you that ConcurrentHashMap is an important class in Java and you will often find yourself dealing with this class in a multithreaded and concurrent Java application. If you are wondering where to start and how to master this essential Java class then you have come to the right place. In this article, I have shared some of the frequently used examples of ConcurrentHashMap in Java-like how to create a ConcurrentHashMap, how to update a key or value, how to delete a key-value pair, how to check if a key exists in ConcurrentHashMap or not, how to add new key-value pairs, and how to retrieve values from ConcurrentHashMap in Java.

Once you have gone through these examples, you will have a better understanding of ConcurrentHashMap and you will be more confident on using them in your Java program without causing subtle bugs that are hard to find and fix.

10 Examples of ConcurrentHashMap in Java


Without wasting any more of your time, here are 10 useful examples of ConcurrentHashMap in Java.

1. How to create a ConcurrentHashMap with default capacity?

        ConcurrentHashMap programmingLanguages = new ConcurrentHashMap();
        System.out.println("Empty ConcurrentHashMap : " + programmingLanguages);

2. How to add objects into ConcurrentHashMap?

        programmingLanguages.put("Java", Integer.valueOf(18));
        programmingLanguages.put("Scala", Integer.valueOf(10));
        programmingLanguages.put("C++", Integer.valueOf(31));
        programmingLanguages.put("C", Integer.valueOf(41));
        System.out.println("ConcurrentHashMap with four mappings : " + programmingLanguages);

3. How to check if a key exists in ConcurrentHashMap or not?

        boolean isJavaExist = programmingLanguages.containsKey("Java");
        boolean isPythonExist = programmingLanguages.containsKey("Python");
        System.out.printf("Does Programming language Map has %s? %b %n", "Java", isJavaExist);
        System.out.printf("Does Programming language Map contains %s? %b %n", "Python", isPythonExist);

4. How to retrieve values from ConcurrentHashMap in Java?

        int howOldIsJava = programmingLanguages.get("Java");
        int howOldIsC = programmingLanguages.get("C");
        System.out.printf("How old is Java programming langugae? %d years %n", howOldIsJava);
        System.out.printf("How old is C langugae? %d years %n", howOldIsC);

5. How to check if a value exists in ConcurrentHashMap?

        boolean is41Present = programmingLanguages.containsValue(Integer.valueOf(41));
        boolean is31Present = programmingLanguages.containsValue(Integer.valueOf(31));
        System.out.printf("Does value 41 is present in ConcurrentHashMap? %b %n", is41Present);
        System.out.printf("Does value 31 is present in ConcurrentHashMap? %b %n", is31Present);

6. How to find Size of ConcurrentHashMap in Java?

        int numberOfMappings = programmingLanguages.size();
        System.out.printf("ConcurrentHashMap %s, contains %d mappings %n",
                programmingLanguages, numberOfMappings);

7. How to loop over ConcurrentHashMap in Java?

There are multiple ways to loop over a ConcurrentHashMap in Java. In fact, you can use all the four ways to iterate over the Map with ConcurrentHashMap as well. Ultimately, it also implements the java.utill.Map interface hence it obeys the contract of Map

        Set&gt; entrySet = programmingLanguages.entrySet();
        for (Map.Entry mapping : entrySet) {
            System.out.printf("Key : %s, Value: %s %n", mapping.getKey(), mapping.getValue());
        }

8. PutIfAbsent Example - Adding keys only if it's not present in ConcurrentHashMap?

        System.out.printf("Before : %s %n", programmingLanguages);
        programmingLanguages.putIfAbsent("Java", 22); // Already exists
        System.out.printf("After : %s %n", programmingLanguages);

        programmingLanguages.put("Python", 23);  // Added
        System.out.printf("After : %s %n", programmingLanguages);

9. How to replace a Mapping in ConcurrentHashMap?

You can use the replace method to update the value of a key in ConcurrentHashMap. This method takes both key and value and updates the old value with the new one as shown below:

        programmingLanguages.replace("Java", 20);
        System.out.println("ConcurrentHashMap After replace : " + programmingLanguages);

10. How to remove key values from ConcurrentHashMap in Java?

You can use the remove() method of ConcurrentHashMap to remove the mapping from the Map. This method will remove both key and values and size of ConcurrentHashMap will decrease by one as shown in the following example:

        programmingLanguages.remove("C++");
        System.out.println("ConcurrentHashMap After remove : " + programmingLanguages);

11. How to remove keys, while Iterating over ConcurrentHashMap?

        Iterator keys = programmingLanguages.keySet().iterator();
        while (keys.hasNext()) {
            System.out.printf("Removing key %s from ConcurrentHashMap %n", keys.next());
            keys.remove();
        }

12. How to check if ConcurrentHashMap is empty in Java?

You can use the isEmpty() method of ConcurrentHashMap to check if the given Map is empty or not. This method will return true if ConcurrentHashMap doesn't have any mapping as shown in following example:

boolean isEmpty = programmingLanguages.isEmpty();
System.out.printf("Is ConcurrentHashMap %s is empty? %b ", programmingLanguages, isEmpty);

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Prep, Oracle Java Exam Prep

ConcurrentHashMap Examples Java


Here is the complete Java Program which you can copy paste in Eclpse or run it from command line to play with:

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

/**
  * Java program to demonstrate how to use Concurrent HashMap in Java by simple examples.
  *
  * @author javin
  */

public class ConcurrentHashMapExamples{

    public static void main(String args[]) {

        // Creates a ConcurrentHashMap with default capacity
        ConcurrentHashMap programmingLanguages = new ConcurrentHashMap();
        System.out.println("Empty ConcurrentHashMap : " + programmingLanguages);


        // Adding objects into ConcurrentHashMap
        programmingLanguages.put("Java", Integer.valueOf(18));
        programmingLanguages.put("Scala", Integer.valueOf(10));
        programmingLanguages.put("C++", Integer.valueOf(31));
        programmingLanguages.put("C", Integer.valueOf(41));
        System.out.println("ConcurrentHashMap with four mappings : " + programmingLanguages);


        // Checking if a key exists in ConcurrentHashMap or not
        boolean isJavaExist = programmingLanguages.containsKey("Java");
        boolean isPythonExist = programmingLanguages.containsKey("Python");
        System.out.printf("Does Programming language Map has %s? %b %n", "Java", isJavaExist);
        System.out.printf("Does Programming language Map contains %s? %b %n", "Python", isPythonExist);


        // Retrieving values from ConcurrentHashMap in Java
        int howOldIsJava = programmingLanguages.get("Java");
        int howOldIsC = programmingLanguages.get("C");
        System.out.printf("How old is Java programming langugae? %d years %n", howOldIsJava);
        System.out.printf("How old is C langugae? %d years %n", howOldIsC);


        // Checking if a value exists in ConcurrentHashMap
        boolean is41Present = programmingLanguages.containsValue(Integer.valueOf(41));
        boolean is31Present = programmingLanguages.containsValue(Integer.valueOf(31));
        System.out.printf("Does value 41 is present in ConcurrentHashMap? %b %n", is41Present);
        System.out.printf("Does value 31 is present in ConcurrentHashMap? %b %n", is31Present);


        // Finding Size of ConcurrentHashMap
        int numberOfMappings = programmingLanguages.size();
        System.out.printf("ConcurrentHashMap %s, contains %d mappings %n",
                programmingLanguages, numberOfMappings);


        // Loop over ConcurrentHashMap in Java
        Set&gt; entrySet = programmingLanguages.entrySet();
        for (Map.Entry mapping : entrySet) {
            System.out.printf("Key : %s, Value: %s %n", mapping.getKey(), mapping.getValue());
        }


        //PutIfAbsent Example - Adding keys only if its not present in ConcurrentHashMap
        System.out.printf("Before : %s %n", programmingLanguages);

        programmingLanguages.putIfAbsent("Java", 22); // Already exists
        System.out.printf("After : %s %n", programmingLanguages);

        programmingLanguages.put("Python", 23);  // Added
        System.out.printf("After : %s %n", programmingLanguages);


        // Replacing a Mapping in ConcurrentHashMap
        programmingLanguages.replace("Java", 20);
        System.out.println("ConcurrentHashMap After replace : " + programmingLanguages);


        // Removing key values from ConcurrentHashMap
        programmingLanguages.remove("C++");
        System.out.println("ConcurrentHashMap After remove : " + programmingLanguages);


        // Removing Keys, while Iterating over ConcurrentHashMap
        Iterator keys = programmingLanguages.keySet().iterator();
        while (keys.hasNext()) {
            System.out.printf("Removing key %s from ConcurrentHashMap %n", keys.next());
            keys.remove();

        }


        // How to check if ConcurrentHashMap is empty
        boolean isEmpty = programmingLanguages.isEmpty();
        System.out.printf("Is ConcurrentHashMap %s is empty? %b ", programmingLanguages, isEmpty);

    }

}

Output:

Empty ConcurrentHashMap : {}
ConcurrentHashMap with four mappings : {C=41, Scala=10, Java=18, C++=31}
Does Programming language Map has Java? true
Does Programming language Map contains Python? false
How old is Java programming langugae? 18 years
How old is C langugae? 41 years
Does value 41 is present in ConcurrentHashMap? true
Does value 31 is present in ConcurrentHashMap? true
ConcurrentHashMap {C=41, Scala=10, Java=18, C++=31}, contains 4 mappings
Key : C, Value: 41
Key : Scala, Value: 10
Key : Java, Value: 18
Key : C++, Value: 31
Before : {C=41, Scala=10, Java=18, C++=31}
After : {C=41, Scala=10, Java=18, C++=31}
After : {C=41, Python=23, Scala=10, Java=18, C++=31}
ConcurrentHashMap After replace : {C=41, Python=23, Scala=10, Java=20, C++=31}
ConcurrentHashMap After remove : {C=41, Python=23, Scala=10, Java=20}
Removing key C from ConcurrentHashMap
Removing key Python from ConcurrentHashMap
Removing key Scala from ConcurrentHashMap
Removing key Java from ConcurrentHashMap
Is ConcurrentHashMap {} is empty? true

That's all about ConcurrentHashMap examples in Java. As I said, after going through these examples, you will have a better understanding of How ConcurrentHashMap works and how to use it properly. Now you have a good idea of how to create, add, update, search, and delete entries on a ConcurrentHashMap in Java.

Monday, February 17, 2020

Difference between include directive, include action and JSTL import tag in JSP?

Oracle Java Tutorial and Materials, Oracle Java Certification, Oracle Java JSTL, Oracle Java Prep

There are three main ways to include the content of one JSP into another:

include directive

JSP include action

and JSTL import tag

The include directive provides static inclusion. It ads content of the resource specified by its file attribute, which could be HTML, JSP or any other resource at translation time.

Any change you make in the file to be included after JSP is translated will not be picked up by include directive.

Since JSP is translated only once but can be requested many times it's not a very useful option. It was originally intended to include static contents like HTML header and footer for a web page.

The main difference between include directive and include action is that JSP includes action provides dynamic inclusion.

The content of another JSP or HTML page is included at request time, which any change you make in the file to be included will be visible to another JSP when requested.

This is ideal if you are importing content from dynamic resources like another JSP page. The file to be included is specified by page attribute of jsp: include tag.

Third option to include the output of one JSP page into another is JSTL import tag. This works pretty much like include action but the main difference between import tag and includes action is that import tag can include resources from the outside world.

If you use include directive or include action you are only limited to include the output of resource from the same project or another web application residing in the same container.

It is the most powerful and flexible way to include the content of one JSP to another. The file to be included is specified by url attribute of import tag.

Oracle Java Tutorial and Materials, Oracle Java Certification, Oracle Java JSTL, Oracle Java Prep

In short

1) The main difference between include directive and include action is that the former is static include while later is dynamic include. Also former uses file attribute to specify the location of the resource to be include while later uses page attribute.

3) The key difference between include action and JSTL import tag is that former can only include local resources but later can also include the output of remote resources, JSP pages or HTML pages outside the web container. include action uses page attribute while import tag uses URL attribute.

That's all on the difference between include direction, include action and JSTL import tag in JSP.

Sunday, February 16, 2020

Right Way to Create, Start and Stop a New Thread in Java

One of the most important task for a Java developer is to learn multi-threading and learn it correctly. There are more Java developers who know multi-threading incorrectly than the programmer who doesn't know at all. In order to learn it correctly, you need to start it from scratch, I mean the most fundamental concepts of multithreading like how to create create, start, and stop a new thread in Java. I am sure you already know that as you have done that a lot of time but it's worth remembering few facts to not repeat the mistakes many programmers do when they write multithreading code in Java. In this article, we'll see a couple of those, mainly while creating, starting, and stop threads in Java. So fasten your seatbelt and let's go little deep into threads in Java.

1. Use start() instead of run()


start creates a new thread and then execute the code on that thread while run just execute the code in the thread which calls the run() method.  I have discussed this already. See this article for a complete discussion.

2. Use Runnable instead of Thread


There are two ways to create a Task for the thread, something which can be executed in parallel, either by implementing Runnable interface and overriding run() method or by extending Thread class and putting your code inside run() method there. Don't get confused between these two run() method they are same Since Thread implements the Runnable interface it gets it from there.

An Example of Creating and Starting Thread in Java

import java.util.Arrays;

public class ThreadBasics{

    public static void main(String args[]) {

        // instance of Runnable implementation for threads
        ParallelTask task = new ParallelTask();
   
   
        // This will only create instance of Thread class
        // it will not start until you call start() method
        Thread T1 = new Thread(task);
        Thread T2 = new Thread(task);
   
        // Starting T1 and T2 thread
        T1.start();
        T2.start();
 
    }

}

/*
 * Always use Runnable to put code which you want to execute parallel
 * Using multiple threads.
 */
class ParallelTask implements Runnable{

    @Override
    public void run() {
       System.out.println(Thread.currentThread().getName() + " is executing ParallelTask");
   
    }

}

Output
Thread-0 is executing ParallelTask
Thread-1 is executing ParallelTask

How to create Daemon Thread in Java


There are two kinds of threads in Java, user thread or daemon thread. Some people also like to say daemon or non-daemon. Difference between a daemon and a user thread is that a user thread runs until the run() method completes either by normally or due to any Exception and prevents your Java application from exiting.

On the other hand, daemon thread will not keep your Java program alive if all user threads already finished execution. As soon as last user thread completes its execution, daemon thread dies, even if they are executing code in their run() method.

By default any thread, it derives its daemon status from the thread which creates it, that's why any thread created by the main thread is always non-daemon, unless and until you make it daemon explicitly by calling the setDaemon() method.

to give you an example let's modify the earlier example to introduce a 3-second sleep in the run() method of ParallelTask class, this will prevent make thread running from longer duration. If both T1 and T2 are non-daemon user threads then your Java program will not terminate until T1 and  T2 finish execution.

On the other hand, if you make them daemon, your Java program will finish as soon as your main thread finishes. Here is the screenshot which will make things clear.

It will even print the following lines before Java program finishes but in case of daemon thread, the program will be abruptly terminated and print statements from T1 and T2 will not be printed.

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Prep, Oracle Java Exam Prep

Main Thread is finished
Thread-1 is finished
Thread-0 is finished

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Prep, Oracle Java Exam Prep

Use Volatile variable to Stop Thread in Java


Unfortunately, there is no direct way to stop the thread in Java. There was a stop() method in java.lang.Thread class but it was long deprecated. This means the only way to stop a thread is to ask him to come out from it's run execution is to get

Saturday, February 15, 2020

Earn Oracle Java Certification and Boost Your Professional Life


Java Certification is one of the most desired Certifications in IT field. Earning a Java Certification will help you to get a dream job. Java Programming is the world's highest used language, no doubt about it. Everyday lot of individuals are coming to Java world because there is always a strong need for Java language. Not only to create have new applications, but new learners required to conceives already written applications in Java. Java/JEE is a vast domain. You can browse any job portal, and you will undoubtedly find amongst all vacant positions Java is in high demand. So it is advised you learn Java language, and to demonstrate your knowledge get certified by Oracle. To help you clear Java Certification, below, we have listed a few tips to make your preparation easy.

Tips to Prepare for Oracle java Certification

1) Mentally Prepare Yourself

Seriously think about why you are getting Java Certification, and why do you want to be Java certified Professional. You have to decide firmly, and you will earn any one of Java Certification which one you opt for your career within the next 3-5 months or so. Try to study with complete dedication.

2) Obtain the Appropriate Study Material

There is a lot of recommendations you obtain your study material, and some applicants study from books, study guides, practice tests, etc.

There are enough resources to provide practice tests to prepare for the Java certification exam. Practice tests help to measure your learning before appear for your actual Java exam. Make sure you get updated and reliable practice tests. Practice tests will also strengthen your confidence. Become a member of the code ranch forum; this is very useful for you, and you will get a lot of helpful answers, tips, and advice from experienced professionals.

3) Approach in Deep

Before start, your Java Certification exam preparation, determine your objectives, and plan your study schedule. Then begin your preparation. Study Both the basic and advanced sessions initially. This will equip you with a good knowledge of concepts. If you have successfully learned the basic and advanced sessions, then you can start taking practice questions available.

4) Register for the Exam

If you already have studied basic and advanced sessions, you should register for the java exam now.

5) Revision

Read one more time to revise the topics. This step is voluntary if you feel you are weak with some topics, and you could not perform well in the practice tests, then you can do this as many time as possible. Go through all the topics one more time.

6) Relax

This is the last part of your study, and there is no u-turn. Don't study a day before the exam. It is necessary to rest and get a good night's sleep. If you follow all the steps above and understand all the topics, you should be more than ready by now.

Why are Java Certifications Important for the IT Professionals?

Java Certifications are a plus point to get jobs quickly because in this competitive world, receiving a job is a challenging task.

Millions of peoples have completed their studies and looking for a job. So to get the first preference for the job opportunity, individuals need the certifications. If you are a Java certified professional, you receive more job opportunities because certifications are the first step or the plus point for the professionals.

Oracle divided the three editions (SE, EE, and ME) into four distinct levels (OCA, OCP, OCE, and OCM) of certifications. On the basis of these levels, you can determine your exam path. Java is the most sought-after technology worldwide because most of the applications are formed in Java technology only. Even smartphones also work on Java technology.

Java field has so many vacant jobs, but the companies give a chance to the certified professionals. The real fact is, "companies strongly believe that certified professionals have the practical experience with the technologies, and also they have definite ideas about the technologies."

This is the only reason all the Java certified professionals point out to all the aspirants, don't rely on the braindumps for your Java certification exam preparation. Learn all the exam topics thoroughly, practice codes. If you follow the dumps, it kills your expertise to deal with technologies; it ruins your working experience, maybe theoretically, you have good knowledge of concepts, but if you do not practice with codes, you could not get expertise in Java language.

So study well, learn the exam objectives thoroughly, Practice with codes, and before sit for your actual Java exam, measure your knowledge level with practice tests.

I hope this article gives you at least some ideas on how to study for the Java certification exam. In any case, if you fail in your exam at the first time, don't get disappointed. You will have more understanding and confidence when you attempt it the next time then the person who passed it on the first attempt.

Friday, February 14, 2020

Difference between CountDownLatch and CyclicBarrier in Java Concurrency

Difference between CountDownLatch and CyclicBarrier in Java


Both CyclicBarrier and CountDownLatch are used to implement a scenario where one Thread waits for one or more Thread to complete their job before starts processing but there is one difference between CountDownLatch and CyclicBarrierin Java which separates them apart and that is, you can not reuse same CountDownLatch instance once count reaches to zero and latch is open, on the other hand, CyclicBarrier can be reused by resetting Barrier, Once barrier is broken.

A useful property of a CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.

A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.

The CyclicBarrier uses a fast-fail all-or-none breakage model for failed synchronization attempts: If a thread leaves a barrier point prematurely because of interruption, failure, or timeout, all other threads, even those that have not yet resumed from a previous await(), will also leave abnormally via BrokenBarrierException (or InterruptedException if they too were interrupted at about the same time).

This diagram also nicely explains the difference between CountDownLatch and CyclicBarrier in Java concurrency:

Oracle Java Study Materials, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Java Prep

That's all about the difference between CountDownLatch and CyclicBarrier in Java. As I said, the key difference is that you can reuse CyclicBarrier but CountDownLatch cannot be reused once count down reaches zero. That's why CyclicBarrier is often used when a task is repeated while CountDownLatch is used for a one-time task like loading initial cache before start accepting client connections.

Btw, If you are serious about improving your understanding of Java concurrency knowledge and skills, I strongly suggest you should read the Java Concurrency in Practice book by Brian Goetz, Joshua Bloch, Doug Lea and team, one of the best resources for Java developers.

Oracle Java Study Materials, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Java Prep

If you find trouble understanding the book and need someone to explain to you those concepts with more examples, you can also join the Java Concurrency in Practice Bundle course by Heinz Kabutz which is based upon this book and makes it easy to understand those tricky concurrency concepts. It's like someone explaining your Java Concurrency in Practice book live.

Oracle Java Study Materials, Oracle Java Tutorial and Material, Oracle Java Exam Prep, Java Prep

Even if you have read the book, going through this course will help you to understand Java Concurrency better and help you to write robust concurrent code with fewer bugs. Sorry, it's almost impossible to write concurrent code without subtle bugs, at least in the first iteration.