Which collection classes are thread-safe in Java?

JavaObject Oriented ProgrammingProgramming

A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.

Stack

The Stack class in Java implements the stack data structure that is based on the principle of LIFO. So, the Stack class can support many operations such as push, pop, peek, search, empty, etc.

Example

import java.util.*;
public class StackTest {
   public static void main (String[] args) {
      Stack<Integer> stack = new Stack<Integer>();
      stack.push(5);
      stack.push(7);
      stack.push(9);
      Integer num1 = (Integer)stack.pop();
      System.out.println("The element popped is: " + num1);
      Integer num2 = (Integer)stack.peek();
      System.out.println(" The element on stack top is: " + num2);
   }
}

Output

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


Vector

An array of objects that grow as required is implemented by the Vector class in Java. The Vector class can support the methods like add(), remove(), get(), elementAt(), size(), etc

Example

import java.util.*;
public class VectorTest {
   public static void main(String[] arg) {
      Vector vector = new Vector();
      vector.add(9);
      vector.add(3);
      vector.add("ABC");
      vector.add(1);
      vector.add("DEF");
      System.out.println("The vector is: " + vector);
      vector.remove(1);
      System.out.println("The vector after an element is removed is: " + vector);
   }
}

Output

The vector is: [9, 3, ABC, 1, DEF]
The vector after an element is removed is: [9, ABC, 1, DEF]
raja
Published on 03-Sep-2019 18:24:15
Advertisements