Thread-Safe Collections in Java

MD Aminul Islam Oct 12, 2023
Thread-Safe Collections in Java

In Java, a thread-safe is a class that guarantees the class’s internal state and that the methods’ values are correct while multiple threads are invoked concurrently.

This tutorial discusses different collection classes via code examples that are thread-safe in java.

Thread Safe Collections in Java

In Java, the most popular thread-safe collection classes are Vector, Stack, Hashtable, Properties, etc. Let’s learn each of them, starting with the Vector below.

Thread Safe Collection Class - Vector

The Vector is an array of objects that can grow as required. This class supports with the method like add(), remove(), get(), elementAt(), and size().

Example Code:

// Importing necessary packages
import java.util.*;

public class JavaVector {
  public static void main(String[] arg) {
    // Declaring a vector
    Vector MyVector = new Vector();

    // Adding data to vector
    MyVector.add(12);
    MyVector.add(3);
    MyVector.add("ABC");
    MyVector.add(10);
    MyVector.add("DEF");
    System.out.println("The vector is: " + MyVector);

    // Removing data from the vector.
    MyVector.remove(1);
    System.out.println("The vector after removing an element is: " + MyVector);
  }
}

Output:

The vector is: [12, 3, ABC, 10, DEF]
The vector after removing an element is: [12, ABC, 10, DEF]

Thread Safe Collection Class - Stack

The Stack class implements the stack data structure. It is based on the LIFO or Last In First Out. The most common operation of the Stack class is push(), pop(), empty(), and search().

Example Code:

// Importing necessary packages
import java.util.*;

public class JavaStack {
  public static void main(String[] args) {
    // Declaring a stack
    Stack<Integer> MyStk = new Stack<Integer>();

    // Adding data to stack
    MyStk.push(5);
    MyStk.push(7);
    MyStk.push(9);

    // POP from the stack
    Integer num1 = (Integer) MyStk.pop();
    System.out.println("The Popped element is: " + num1);

    // PUSH the stack
    Integer num2 = (Integer) MyStk.peek();
    System.out.println("The top element is: " + num2);
  }
}

Output:

The popped element is: 9
The top element is: 7

Thread Safe Collection Class - Hashtable

The Java Hashtable class implements the hash table that maps the keys to values. In addition, it implements the Map interface and inherits the directory.

Example Code:

// Importing necessary packages
import java.util.*;

public class JavaHashtable {
  public static void main(String args[]) {
    // Declaring a HashTable
    Hashtable<Integer, String> HTable = new Hashtable<Integer, String>();

    // Adding data to HashTable
    HTable.put(100, "This");
    HTable.put(102, "is");
    HTable.put(101, "a");
    HTable.put(103, "data");

    for (Map.Entry MyMap : HTable.entrySet()) {
      // Extracting data and keys from the HashTable
      System.out.println(MyMap.getKey() + " " + MyMap.getValue());
    }
  }
}

Output:

103 data
102 is
101 a
100 This

Thread Safe Collection Class - Synchronize HashMap

There is a synchronized version of HashMap that you can use as a thread-safe collection in Java. This HashMap works most similar to the Synchronize HashMap.

Example Code:

// Importing necessary packages
import java.util.*;

public class JavaHashMap {
  public static void main(String[] args) throws Exception {
    try {
      // Declaring a HashMap
      Map<String, String> HMap = new HashMap<String, String>();

      // Adding values to the HashMap
      HMap.put("1", "This");
      HMap.put("2", "is");
      HMap.put("3", "a");
      HMap.put("4", "sample");
      HMap.put("5", "data");

      // Printing the value of HashMap
      System.out.println("The Map is : " + HMap);

      // Synchronizing the HashMap
      Map<String, String> SMap = Collections.synchronizedMap(HMap);

      // Printing the Collection after synchronizing the HashMap
      System.out.println("The synchronized map is : " + SMap);
    } catch (IllegalArgumentException e) {
      // Printing exception if necessary
      System.out.println("Exception thrown : " + e);
    }
  }
}

Output:

The Map is : {1=This, 2=is, 3=a, 4=sample, 5=data}
The synchronized map is : {1=This, 2=is, 3=a, 4=sample, 5=data}
MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - Java Collection