Safe list copy : Collections Threads « Threads « Java






Safe list copy

Safe list copy
   

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

public class SafeListCopy extends Object {
  public static void printWords(String[] word) {
    System.out.println("word.length=" + word.length);
    for (int i = 0; i < word.length; i++) {
      System.out.println("word[" + i + "]=" + word[i]);
    }
  }

  public static void main(String[] args) {
    List wordList = Collections.synchronizedList(new ArrayList());

    wordList.add("Synchronization");
    wordList.add("is");
    wordList.add("important");

    String[] wordA = (String[]) wordList.toArray(new String[0]);

    printWords(wordA);

    String[] wordB;
    synchronized (wordList) {
      int size = wordList.size();
      wordB = new String[size];
      wordList.toArray(wordB);
    }

    printWords(wordB);

    // Third technique (the 'synchronized' *is* necessary)
    String[] wordC;
    synchronized (wordList) {
      wordC = (String[]) wordList.toArray(new String[wordList.size()]);
    }

    printWords(wordC);
  }
}

           
         
    
    
  








Related examples in the same category

1.Java 1.5 (5.0) new features: PriorityQueueJava 1.5 (5.0) new features: PriorityQueue
2.Safe vector copySafe vector copy
3.Safe collection operationSafe collection operation
4.Java 1.5 (5.0) new feature: collection and thread
5.Java Thread Performance: Collection Test
6.Java Thread Performance: AtomicTest
7.Rhyming WordsRhyming Words
8.Communicate between threads using a Queue
9.Using a Thread-Local Variable
10.A work queue is used to coordinate work between a producer and a set of worker threads.
11.Return a value from a thread.
12.A multithreaded queue used for implementing producer-consumer style threading patternsA multithreaded queue used for implementing producer-consumer style threading patterns
13.Customized java.util.ArrayList: operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes.
14.Customized java.util.HashMap: operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes.
15.Customized java.util.TreeMap: operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes.
16.Current set