Skip to main content

Posts

Showing posts from December, 2020

How to Synchronize Java HashSet

This post shows how to synchronize HashSet in Java and the HashSet’s thread safe alternative which can be used instead of a HashSet. HashSet is not thread safe HashSet in Java is not thread safe as it is not synchronized by default . If you are using HashSet in a multi-threaded environment where it is accessed by multiple threads concurrently and structurally modified too by even a single thread then it must be synchronized externally. A structural modification is defined as any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification. Options for thread-safe Set If you want to synchronize HashSet in Java or looking for a thread-safe alternative of HashSet then there are following options. Use Collections.synchronizedSet() to synchronize Set - This method returns a synchronized (thread-safe) set backed by the specified set. Using CopyOnWriteArraySet - Another opti

HashSet Internal Implementation in Java

HashSet internal implementation in Java or how does HashSet work internally in Java is a very important interview question. Some of the important points that you should know are- What is the backing data structure for HashSet or where does HashSet stores its element? How does add() method work in HashSet? How does remove() method work in HashSet? How elements are retrieved from HashSet? In this post we’ll go through the internal implementation of HashSet in Java and try to explain the above mentioned points. Note that all the code snippet of the HashSet class provided in this post are from JDK 10. Since HashSet internally uses HashMap for its operations so knowing  HashMap Internal Implementation in Java  will help a lot in understanding internal implementation of HashSet. Where does HashSet store its element Internally HashSet in Java uses HashMap to store its elements. With in HashSet class a HashMap is defined that is used to store its elements. private tr

How to Iterate a Java HashSet

In this post we’ll see different ways to iterate a Set or HashSet in Java . Your options to iterate a HashSet are as follows- You can use For-Each loop (Advanced or enhanced for loop), available from Java 5. You can iterate a HashSet using Iterator. Using iterator() method you can get an iterator and then using the hashNext() and next() method of the iterator you can iterate a HashSet. You can also use forEach statement available from Java 8 to loop through Set. Java HashSet iteration example Here is a Java example code that shows all of the above mentioned ways to loop a Set in Java. public class SetIteration { public static void main(String[] args) { Set<String> capitalSet = new HashSet<String>(); // adding elements capitalSet.add("New Delhi"); capitalSet.add("Lisbon"); capitalSet.add("Buenos Aires"); capitalSet.add("Beijing"); System.out.println("**Iterating HashSet using

CountDownLatch in Java With Examples

CountDownLatch in Java is a synchronization aid that allows one or more threads to wait for a set of operations being performed in other threads to complete. CountDownLatch class was added in Java 1.5 and it is part of java.util.concurrent package in Java. Table of contents How CountDownLatch works in Java Java CountDownLatch constructor Java CountDownLatch methods CountDownLatch Java example CountDownLatch in Java is not reusable How CountDownLatch works in Java A CountDownLatch is initialized with a given count then there are two methods await() and countDown() that block and release the threads. await() - Causes the current thread to wait until the latch has counted down to zero. countDown() - Decrements the count of the latch, releasing all waiting threads if the count reaches zero. CountDownLatch as the name itself goes can be thought of as fastening the latch so that the current thread is blocked when await method is called and w

CyclicBarrier in Java With Examples

The java.util.concurrent package provides many synchronizer utilities that cover the use cases where several thread communicate with each other and some sort of synchronizer is needed to regulate that interaction among the threads. CyclicBarrier in Java is one such synchronization aid that is useful when you want threads to wait at a common execution point until all the threads in the set have reached that common barrier point. Table of contents CyclicBarrier class in Java How CyclicBarrier works in Java CyclicBarrier constructors CyclicBarrier methods CyclicBarrier Java example What happens when await method is called BrokenBarrierException in CyclicBarrier CyclicBarrier is reusable CyclicBarrier class in Java CyclicBarrier class was added in Java 1.5 and it is part of java.util.concurrent package in Java. The class is named as CyclicBarrier because it can be reused after the waiting threads are released. How CyclicBarrier works in Jav

Java ListIterator With Examples

In Java there is an Iterator interface which provides an iterator over a collection (List, Set etc.) but there is another interface ListIterator in Java which provides an iterator exclusively for lists like ArrayList , LinkedList , CopyOnWriteArrayList . While iterator can only move forward, ListIterator provides functionality to traverse the List in either direction; forward or backward, which is one of the difference between Iterator and ListIterator in Java. Other differences are as follows. Both of these interfaces have remove() method to safely remove an element from List after the iterator is created but ListIterator has an add() method too. ListIterator also has a set() method to change the element while iterating a List. No current element in ListIterator A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next() . Fo

How to Sort Java ArrayList

ArrayList in Java is an ordered collection in the sense that it maintains the insertion order of the elements but sometimes you may have a requirement to sort an ArrayList in ascending order or descending order. In this post we’ll see How to sort an ArrayList in Java . Table of contents Methods used to sort Java ArrayList Sorting Java ArrayList example Sorting Java ArrayList in descending order Sorting Arraylist using reverseOrder method Sorting Arraylist by providing own custom Comparator Methods used to sort Java ArrayList Collections class in Java provides many utility methods that operate on collections, this class also has sort method. Actually sort() method is overloaded in Collections class and there are 2 variants. void sort(List list) - Sorts the specified list into ascending order, according to the natural ordering of its elements. sort(List list, Comparator<? super T> c) - Sorts the specified list according to the order induced

How to Iterate Java ArrayList

In this post we’ll see different ways to iterate an ArrayList in Java . Your options to iterate an ArrayList are as follows- Using normal for loop Using For-Each loop (Advanced for loop), available from Java 5 Using Iterator or ListIterator (Use ListIterator only if you want to iterate both forward and backward rather than looping an ArrayList sequentially). Using forEach statement available from Java 8 Iterate an ArrayList in Java Example Here is a Java example code that shows all of the above mentioned ways to loop an ArrayList. import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class ArrayListIteration { public static void main(String[] args) { List<String> nameList = new ArrayList<String>(); // adding elements nameList.add("Adam"); nameList.add("Amy"); nameList.add("Jim"); nameList.add("Leo"); System.out.println

Comparable Vs Comparator in Java

Comparable and Comparator in Java are two interfaces used to sort a collection of objects. The obvious question is why two interfaces when they both do the same task of sorting the objects. In this post we’ll see what are Comparable and Comparator interfaces in Java, why both are required and differences between Comparable and Comparator in Java. Table of contents Comparable interface in Java Comparator interface in Java Comparable and Comparator Java example Difference between Comparable and Comparator in Java Comparable interface in Java Comparable interface in Java has a single method compareTo() . int compareTo(T o) - This method compares the object used to call the method with the object passed as parameter for ordering. The objects of the class implementing this interface are ordered as per the implementation of the compareTo() method. Since the class itself is implementing the interface so the ordering as provided by Comparable interface is referred

ArrayList Vs LinkedList in Java

In Java Collections framework there are two general-purpose List implementations— ArrayList and LinkedList . In this post we'll see the differences between ArrayList and LinkedList in Java to understand these two implementations better. Knowing the differences between ArrayList and LinkedList will also help you to determine which implementation is better in which scenario. ArrayList Vs LinkedList in Java 1- How they are internally implemented - ArrayList internal implementation uses an array to store its element. The size of the array can be increased dynamically if needed that is why ArrayList is known as the resizeable array implementation. LinkedList is internally implemented as a doubly linked list where elements are stored as object of type node. In the node object apart from the element, references of the previous and next nodes are also stored. 2- Initial capacity - ArrayList has a constructor ArrayList(int initialCapacity) which can construct an ArrayList of t

Java ConcurrentHashMap With Examples

ConcurrentHashMap in Java is a thread safe Map implementation which provides another alternative to be used in a multithreaded environment apart from HashTable or explicitly synchronizing HashMap . ConcurrentHashMap is part of the java.util.concurrent package. Table of contents How is ConcurrentHashMap a better option Internal implementation of ConcurrentHashMap in Java Java ConcurrentHashMap constructors Java example creating a ConcurrentHashMap Null not allowed in Java ConcurrentHashMap ConcurrentHashMap in Java is thread safe Java ConcurretHashMap returns a fail-safe iterator Atomic operations in ConcurrentHashMap Advantages and disadvantages of ConcurrentHashMap How is ConcurrentHashMap a better option Other thread safe implementations like HashTable or explicit synchronization of HashMap synchronize all the methods on a single lock and all the methods are synchronized , even if methods are for retrieving elements. That makes these opt