了解同步的行为 [英] Understanding the behaviour of Synchronized

查看:140
本文介绍了了解同步的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提高我对在同步调用期间发出的锁定范围的理解。

I'm trying to improve my understanding of the scope of the lock issued during a synchronized call.

Eg:

class CopyOnReadList<T> {

    private final List<T> items = new ArrayList<T>();

    public void add(T item) {
        items.add(item);
    }

    public List<T> makeSnapshot() {
        List<T> copy = new ArrayList<T>();
        synchronized (items) {
            // Make a copy while holding the lock.
            for (T t : items) copy.add(t);
        }
        return copy;
    }

}

href =http://stackoverflow.com/a/3943310/59015>此优秀答案)

(Code lovingly borrowed from this excellent answer)

在此代码段中,可以调用一个线程调用 add ,而另一个正在调用 makeSnapshot ?也就是说, synchronized(items)创建的锁定会影响对的所有尝试读取, makeSnapshot()方法?

In this code snippet, can one thread call add while another is calling makeSnapshot?. Ie., does the lock created by synchronized (items) affect all attempted reads to items, or only those attempted through the makeSnapshot() method?

原始帖子实际使用 c $ c>锁定添加方法:

The original post actually used a synchonized lock in the add method:

public void add(T item) {
    synchronized (items) {
        // Add item while holding the lock.
        items.add(item);
    }
}

删除此操作的副作用是什么? p>

What is the side effect of removing this?

推荐答案

它只影响在makeSnapshot()中尝试的那些方法,更一般的说,

It affects only those attempted in makeSnapshot() or, more generally, any other method that has synchronized(items) block (it means that it will try to aquire lock on items object and block until it's possible).

从add()方法中删除同步块的副作用是add()将会

The side effect of removing synchronized block from add() method is that add() will not try to synchronize on items object, and therefore will allow concurrent modifications, including while makeSnapshot() is executing.

如果没有在add()中同步,你可以有其他线程添加元素到正在创建快照的项目集合。

Without synchronize in add() you can have other threads add elements to items collection WHILE the snapshot is being made.

这篇关于了解同步的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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