简体   繁体   中英

Is it possible to allow different thread both read to and write from the same collection?

I have the following wrapper:

public UserContianer{

    private List<User> users;


    public void add(User u){
         users.add(u)
    }

    public void update(User u){
        if(users.contains(u))
             //updating with the new value u
    }

    public User get(int index){
        return users.get(index);
    }
}

I need to allow multiple thread to read from and write the container simultaneously such that

  • if read and written element of the list are different- that should be ok
  • if read and written element of the list are the same then

    • if there's already a thread updating the element all read operation should be blocked untill the write operation's finished

    • if there's a thread reading some element, all write operations should be blocked until the reading's finished

First of all, are such requirements even make sense? I'm new to multithreading and maybe that's actualy not what I wanted.

Secondly, is it possible to implement the requirements in Java?

One option is to wrap your existing List in a synchronized version with Collections.synchronizedList(List<T> list) . This allows thread-safe use of the List, if all access is through the synchronized wrapper.

Note that the elements in the List are references . If you want to lock the List while you're making changes to objects, you'll need to synchronize at a higher level. One way to do this is to mark methods as synchronized .

 public synchronized void update(User u) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM