Thursday, January 3, 2008

How to avoid ConcurrentModificationException?

java.util.ConcurrentModificationException is a kind of runtime exception that happens when a thread iterates a vector while another thread changes the element of vector, either add or remove element. This exception encountered mostly at multithreaded application.
To avoid this exception, simply add synchronized keyword to the methods that access the vector. This will guarantee that only one thread can access the vector at a time.


Example:

class Collections {
private Vector collection = new Vector();

synchronized void displayElement(){
Iterator it = collection.iterator();
while (it.hasNext()){
System.out.println((String)it.next());
}
}

synchronized String removeElement(int index) throws Exception {
return (String) collection.remove(index);
}

synchronized boolean addElement(String element) throws Exception {
return collection.add(element);
}
}



Please note that adding synchronized keyword will decrease the performance, especially for realtime application. So be carefull.

Sunday, December 30, 2007

What is JVM?

JVM stands for Java Virtual Machine, a java runtime environment required to run java programs in any operating system. JVM includes java interpreter that handle the native function call to operating system. A different JVM is required for each unique operating system (Linux, OS/2, Windows 98, etc.), but any JVM can run the same version of a Java program. JVM will interpret the java program appropriate with the operating system where the java program runs, so programmer no need to worry about how the code is excecuted. Thats's how the java motto actually works, 'Write Once Run Anywhere'.