Given, that **add method defination in ArrayList** is as follows :-
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
Please find following program to check Thread safety of ArrayList.
package pack4;
import java.util.ArrayList;
public class Demo {
public static void main(String[] args) {
ArrayList al = new ArrayList() ;
new AddFirstElementThread(al).start() ;
new RemoveFirstElementThread(al).start() ;
}
}
class AddFirstElementThread extends Thread{
ArrayList list ;
public AddFirstElementThread(ArrayList l) {
list = l ;
}
@Override
public void run() {
while(true){
if(list.size() == 0){
list.add("First element") ;
}
}
}
}
class RemoveFirstElementThread extends Thread{
ArrayList list ;
public RemoveFirstElementThread(ArrayList l) {
list = l ;
}
@Override
public void run() {
while(true){
if(list.isEmpty()){
try{
list.get(0) ;
System.out.println("Hence Proved, that ArrayList is not Thread-safe.");
System.exit(1) ;
}catch (Exception e) {
//continue, if no value is there at index 0
}
}
}
}
}
But, the program never terminates, thus fails to prove thread-safety of ArrayList.
Please, suggest correct implementation to test Thread-safe behaviour of ArrayList and Vector.
Thanks & Best Regards,
Rits Well, tha thing is.. ArrayList is not thread safe, so you won't be able to test it is in first place.
以上就是ArrayList ThreadSafety Test Code fails的详细内容,更多请关注web前端其它相关文章!