Thread Safe LinkedList (ConcurrentLinkedDeque) Example

java.util.concurrent.ConcurrentLinkedDeque is the thread safe implementation for LinkedList. This is same as LinkedList except the thread safe feature. Here is one example to add and remove items in ConcurrentLinkedDeque. If we are using this example with LinkedList it will throw ConcurrentModification Exception.

Example

package com.vinod.concurrency;
import java.util.concurrent.ConcurrentLinkedDeque;
/**
 * Thread safe implementation of linked list.
 * 
 * @author vinod.kumaran
 *
 */
public class ConcurrentLinkedDequeExample {
	public static void main(String[] args) {
		ConcurrentLinkedDeque<String> linkedList = new ConcurrentLinkedDeque<String>();
		// List<String> linkedList = new LinkedList<String>();
		linkedList.add("sunday");
		linkedList.add("monday");
		linkedList.add("tuesday");
		for (String s : linkedList) {
			System.out.print(s + "->");
			linkedList.remove("sunday");
		}
		System.out.println(linkedList);
	}
}

Output



sunday->monday->tuesday->[monday, tuesday]



No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts