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

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts