WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Intermediate · question 36 of 100

How do you create a synchronized List in Java Collections?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

In Java, you can create a synchronized List using the Collections.synchronizedList() method. This method returns a synchronized (thread-safe) view of the specified list. All access to the returned list is synchronized on a common lock.

Here’s an example code that demonstrates how to create a synchronized List:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("One");
        list.add("Two");
        list.add("Three");
    
        List<String> synchronizedList = Collections.synchronizedList(list);
    
        // Access the synchronized list in a synchronized block
        synchronized (synchronizedList) {
            System.out.println("Iterating through synchronized list:");
            for (String element : synchronizedList) {
                System.out.println(element);
            }
        }
    }
}

In this example, we create an ArrayList and add three strings to it. We then create a synchronized view of the ArrayList using the Collections.synchronizedList() method. Finally, we access the synchronized list in a synchronized block and iterate through its elements.

Note that while the synchronized list is thread-safe for individual method calls, it’s not sufficient to synchronize on the list itself if you need to perform compound operations (like iteration or conditionally accessing and modifying the list), as that would not guarantee the required atomicity of the operations. Instead, you would need to manually synchronize on a common lock for those operations, or consider using more advanced concurrency mechanisms like the java.util.concurrent package.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics