ArrayList ThreadSafety Test Code fails

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前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏