避免与列表可能并发问题被退回 [英] Avoiding a possible concurrency issue with a LIST being returned

查看:103
本文介绍了避免与列表可能并发问题被退回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是打扰我乞讨标准补救并发问题的顺序

Here is the sequence that bother me begging a standard remedy for a concurrency issue


  1. 创建一个列表对象(LST)

  2. 启动multple线程(线程更新)

  3. 发送的LST每个线程更新程序更新(添加)吧。

  4. 等待一段规定的时间(T1),让更新线程的更新继续。

  5. 后T1时间到期,回报善堂到另一个应用程序(消费者-APP),是不是在我们的控制。

  6. 当其返回,更新线程可能仍然更新LST。

  7. 消费-应用不知道是否名单仍在由更新线程后台更新。

  8. 消费应用程序内待办事项操作(添加/删除)上的LST。

问题:这会导致并发问题。

Problem : This will lead to concurrency issue.

如何解决呢?

如何有效地制止T1之后更新的主题?或者是有处理这个任意标准的方式?请问 synchronizedList(Collections.synchronizedList(新的ArrayList()))此帮助?

How to stop updating threads after t1 effectively? Or is there any standard way to deal on this? Will the synchronizedList (Collections.synchronizedList(new ArrayList())) help in this?

编辑:
我知道的CopyOnWriteArrayList也。但我专注于简单的ArrayList这个

Edit : I'm aware of the CopyOnWriteArrayList also. But I'm focusing on the simple ArrayList on this

推荐答案

您可以使用一个执行者服务,创建和终止线程,与解决并发性的CopyOnWriteArrayList一起。

You could use a executor service to create and terminate threads, along with a CopyOnWriteArrayList that address concurrency.

 private CopyOnWriteArrayList<someObject> someArrayList = new CopyOnWriteArrayList<someObject>();

...

 class NodeStatusThread implements Runnable {

        private ExecutorService UpdaterThreadExecutor = null;
        private int numThrd = 20; //threads 
        private int timeout = 10; // ten-seconds 

        @Override
        public void run() {
            for (int i=0;i<numThrd; i++ ) {
                UpdaterThreadExecutor.execute(new UpdaterThread());
            }
            UpdaterThreadExecutor.shutdown();


            try{
                //Wait for thread completion
                if(!UpdaterThreadExecutor.awaitTermination(timeout, TimeUnit.SECONDS)){  //return false is timeout is surpassed
                    UpdaterThreadExecutor.shutdownNow(); //forces thread termination
                }
            }catch(InterruptedException e){
                UpdaterThreadExecutor.shutdownNow();
            }

        }

}

...

 class UpdaterThread implements Runnable { 

    @Override
    public void run() {
        omeArrayList.add(someObject);

        someArrayList.remove(someObject);
    }
 }

这篇关于避免与列表可能并发问题被退回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆