Java – Make Collection Read Only

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Main {
   public static void main(String[] argv)
   throws Exception {
      List stuff = Arrays.asList(new String[] { "a", "b" });
      List list = new ArrayList(stuff);
      list = Collections.unmodifiableList(list);
      try {
         list.set(0, "new value");
      }
	  catch (UnsupportedOperationException e) {
      }
      Set set = new HashSet(stuff);
      set = Collections.unmodifiableSet(set);
      Map map = new HashMap();
      map = Collections.unmodifiableMap(map);
      System.out.println("Collection is read-only now.");
   }
}

Java – Set Thread Priority

public class Main {
   public static void main(String[] args)
   throws Exception {
      Thread thread1 = new Thread(new TestThread(1));
      Thread thread2 = new Thread(new TestThread(2));
      thread1.setPriority(Thread.MAX_PRIORITY);
      thread2.setPriority(Thread.MIN_PRIORITY);
      thread1.start();
      thread2.start();
      thread1.join();
      thread2.join();
      System.out.println("The priority has been set.");
   }
}

Java – Handle EmptyStackException

import java.util.Date;
import java.util.EmptyStackException;
import java.util.Stack;

public class ExceptionalTest {
   public static void main(String[] args) {
      int count = 1000000;
      Stack s = new Stack();
      System.out.println("Testing for empty stack");
      long s1 = System.currentTimeMillis();
      for (int i = 0; i <= count; i++)
      if (!s.empty())
         s.pop();
      long s2 = System.currentTimeMillis();
      System.out.println((s2 - s1) + " milliseconds");
      System.out.println("Catching EmptyStackException");
      s1 = System.currentTimeMillis();
      for (int i = 0; i <= count; i++) {
         try {
            s.pop();
         }
         catch (EmptyStackException e) {
         }
      }
      s2 = System.currentTimeMillis();
      System.out.println((s2 - s1) + " milliseconds");
   }
}

Page 1 of 3123