简体   繁体   中英

How to thread-safely manipulate lists in Java?

I have a simple class with a linked list:

private final LinkedList<Object> list;

If I have two methods manipulating this list:

public void m1(){ ... list.poll()...}

public void m2(){...list.clear)....}

How do I make sure of ThreadSafety? Is it enough to have both methods receive the "synchronized" keyword, or am I required to put a

synchronized(list){
    System.out.println("locking on :"  + lock);
}

around the method-code?

Common sense tells me it is the second, but I would like confirmation, OR an easier way to make sure my list does not get messed up.

PS: Or would this be better placed in CodeReview? It feels more in place here, somehow.

将您的列表传递给java.util.Collections类中的public static <T> List<T> synchronizedList(List<T> list)方法,以创建线程安全列表。

It is better to make synchronization as specific as possible instead of marking the whole method with the keyword. The more refined your synchronization is the better your code will perform. Should suggest the latter code that you have shown and synchronize on the same lock when working with the list among threads.

As in your case if you do as below as you have shown it should be okay:

synchronized(list){
    // do something with your list
    // synchronizing on the same lock makes sure other threads have to wait for this lock
    // to be released. In your case you are using the list object as the lock.
}

java.util.Vector是线程安全的,此类中的所有方法都已synchronized

提示:如果要实现某种生产者/消费者模式,请使用现有工具-实现“阻塞队列”的类应满足您的需求

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