为什么vector需要和synchronized同时使用

super254 2009-12-19 10:49:08
为什么对obs的操作都加上了synchronized
/*
* @(#)Observable.java 1.38 04/01/12
*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/

package java.util;

/**
* This class represents an observable object, or "data"
* in the model-view paradigm. It can be subclassed to represent an
* object that the application wants to have observed.
* <p>
* An observable object can have one or more observers. An observer
* may be any object that implements interface <tt>Observer</tt>. After an
* observable instance changes, an application calling the
* <code>Observable</code>'s <code>notifyObservers</code> method
* causes all of its observers to be notified of the change by a call
* to their <code>update</code> method.
* <p>
* The order in which notifications will be delivered is unspecified.
* The default implementation provided in the Observable class will
* notify Observers in the order in which they registered interest, but
* subclasses may change this order, use no guaranteed order, deliver
* notifications on separate threads, or may guarantee that their
* subclass follows this order, as they choose.
* <p>
* Note that this notification mechanism is has nothing to do with threads
* and is completely separate from the <tt>wait</tt> and <tt>notify</tt>
* mechanism of class <tt>Object</tt>.
* <p>
* When an observable object is newly created, its set of observers is
* empty. Two observers are considered the same if and only if the
* <tt>equals</tt> method returns true for them.
*
* @author Chris Warth
* @version 1.38, 01/12/04
* @see java.util.Observable#notifyObservers()
* @see java.util.Observable#notifyObservers(java.lang.Object)
* @see java.util.Observer
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
* @since JDK1.0
*/
public class Observable {
private boolean changed = false;
private Vector obs;

/** Construct an Observable with zero Observers. */

public Observable() {
obs = new Vector();
}

/**
* Adds an observer to the set of observers for this object, provided
* that it is not the same as some observer already in the set.
* The order in which notifications will be delivered to multiple
* observers is not specified. See the class comment.
*
* @param o an observer to be added.
* @throws NullPointerException if the parameter o is null.
*/
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}

/**
* Deletes an observer from the set of observers of this object.
* Passing <CODE>null</CODE> to this method will have no effect.
* @param o the observer to be deleted.
*/
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}

/**
* If this object has changed, as indicated by the
* <code>hasChanged</code> method, then notify all of its observers
* and then call the <code>clearChanged</code> method to
* indicate that this object has no longer changed.
* <p>
* Each observer has its <code>update</code> method called with two
* arguments: this observable object and <code>null</code>. In other
* words, this method is equivalent to:
* <blockquote><tt>
* notifyObservers(null)</tt></blockquote>
*
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#hasChanged()
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void notifyObservers() {
notifyObservers(null);
}

/**
* If this object has changed, as indicated by the
* <code>hasChanged</code> method, then notify all of its observers
* and then call the <code>clearChanged</code> method to indicate
* that this object has no longer changed.
* <p>
* Each observer has its <code>update</code> method called with two
* arguments: this observable object and the <code>arg</code> argument.
*
* @param arg any object.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#hasChanged()
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal;

synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
* needs synchronization, but notifying observers
* does not (should not). The worst result of any
* potential race-condition here is that:
* 1) a newly-added Observer will miss a
* notification in progress
* 2) a recently unregistered Observer will be
* wrongly notified when it doesn't care
*/
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}

for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}

/**
* Clears the observer list so that this object no longer has any observers.
*/
public synchronized void deleteObservers() {
obs.removeAllElements();
}

/**
* Marks this <tt>Observable</tt> object as having been changed; the
* <tt>hasChanged</tt> method will now return <tt>true</tt>.
*/
protected synchronized void setChanged() {
changed = true;
}

/**
* Indicates that this object has no longer changed, or that it has
* already notified all of its observers of its most recent change,
* so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
* This method is called automatically by the
* <code>notifyObservers</code> methods.
*
* @see java.util.Observable#notifyObservers()
* @see java.util.Observable#notifyObservers(java.lang.Object)
*/
protected synchronized void clearChanged() {
changed = false;
}

/**
* Tests if this object has changed.
*
* @return <code>true</code> if and only if the <code>setChanged</code>
* method has been called more recently than the
* <code>clearChanged</code> method on this object;
* <code>false</code> otherwise.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#setChanged()
*/
public synchronized boolean hasChanged() {
return changed;
}

/**
* Returns the number of observers of this <tt>Observable</tt> object.
*
* @return the number of observers of this object.
*/
public synchronized int countObservers() {
return obs.size();
}
}
...全文
347 27 打赏 收藏 转发到动态 举报
写回复
用AI写文章
27 条回复
切换为时间正序
请发表友善的回复…
发表回复
super254 2009-12-22
  • 打赏
  • 举报
回复
[Quote=引用 22 楼 michaellufhl 的回复:]
请注意notifyObservers()里面synchronized块。
为了不把上了锁的Observable传到Observer.update()里面去,程序首先在synchronized块里面做了个snapshot(arrLocal)。
而且那些deleteObservers()函数的synchronize是Observable自己,而非Observable.obs.

Hope I express it clearly.
[/Quote]
谢谢你的答复,前面的说的很有道理,我想问下:deleteObservers()函数前面加不加synchronize对程序处理并发上会有影响吗
super254 2009-12-22
  • 打赏
  • 举报
回复
[Quote=引用 17 楼 sean1203 的回复:]
好结贴了
懂的人没空答
不懂得的人回答不来
没人答是你自己的原因
别怪其他人
[/Quote]
谢谢你的支持,这个问题我会一直跟下去,没有答案是不会结贴的
sean1203 2009-12-22
  • 打赏
  • 举报
回复
mark
super254 2009-12-22
  • 打赏
  • 举报
回复
问题已解决,答案请参照
http://blog.csdn.net/super254/archive/2009/12/22/5055507.aspx
谢谢大家参与
ahhh90h 2009-12-21
  • 打赏
  • 举报
回复
学习
michaellufhl 2009-12-21
  • 打赏
  • 举报
回复
请注意notifyObservers()里面synchronized块。
为了不把上了锁的Observable传到Observer.update()里面去,程序首先在synchronized块里面做了个snapshot(arrLocal)。
而且那些deleteObservers()函数的synchronize是Observable自己,而非Observable.obs.

Hope I express it clearly.
amdgaming 2009-12-21
  • 打赏
  • 举报
回复

先好好去理解 锁synchronized 这个关键字真正含义,
同步?避免脏数据?互斥? 搞的清清楚楚 就知道了

然后 去jdk里看看 这个 东东

static
<T> Collection<T>
synchronizedCollection(Collection<T> c)
返回由指定 collection 支持的同步(线程安全的)collection。
static
<T> List<T>
synchronizedList(List<T> list)
返回由指定列表支持的同步(线程安全的)列表。
static
<K,V> Map<K,V>
synchronizedMap(Map<K,V> m)
返回由指定映射支持的同步(线程安全的)映射。
static
<T> Set<T>
synchronizedSet(Set<T> s)
返回由指定 set 支持的同步(线程安全的)set。
static
<K,V> SortedMap<K,V>
synchronizedSortedMap(SortedMap<K,V> m)
返回由指定有序映射支持的同步(线程安全的)有序映射。
static
<T> SortedSet<T>
synchronizedSortedSet(SortedSet<T> s)

smartcatiboy 2009-12-21
  • 打赏
  • 举报
回复
不懂,Vector不是线程安全的吗???
somesky 2009-12-21
  • 打赏
  • 举报
回复
学习ing
whut_lcy 2009-12-21
  • 打赏
  • 举报
回复
Vector是ArrayList的子类,二者唯一区别就是Vector是线程安全的。
这有好处也有不好的。好处就是保证存取的数据不会出现不一致或者脏数据;不好的呢就是访问效率在多线程下会比ArrayList慢(因为引入了多线程)

而ArrayList与Vector正好相反。

用法:
1)在多线程环境下用Vector即可,你无须担心并发问题;但ArrayList的话你就必须自己注意保证对ArrayList访问的线程安全性。当然,jdk的集合框架已经帮你搞定了,你无须自己实现,就在
java.util.Collections.synchronizedList方法,返回一个线程安全的List
对应的还有Set,Map等等。你可以找JDK文档,里面有很详细的用法

2)在非多线程环境,建议不要用Vector,没有这个必要,而且会降低存取效率。直接用ArrayList即可

一句话,Vector与ArrayList在线程安全上的特点,类似LinkedList(链表)和ArrayList(矩阵/数组)在插入数据与检索数据上的平衡一样。LinkedList插入数据快但检索没有ArrayList慢,反之亦然。

所以,要结合你的具体应用场景来谈。


super254 2009-12-21
  • 打赏
  • 举报
回复
俺就不信了,就没人关注下基础的东西
sean1203 2009-12-21
  • 打赏
  • 举报
回复
好结贴了
懂的人没空答
不懂得的人回答不来
没人答是你自己的原因
别怪其他人
super254 2009-12-21
  • 打赏
  • 举报
回复
看来论坛堕落了。。。。。。。。。。
sean1203 2009-12-20
  • 打赏
  • 举报
回复
对20分的帖子
没人那么感兴趣
小红花是很重要的哦
Dan1980 2009-12-20
  • 打赏
  • 举报
回复
因为Vector是JAVA 2之前的遗留类。JAVA 2对类库进行了重大重构,新加入的集合类如ArrayList,HashMap等都不再是线程安全的,而是用Collections.SynchronizedXXX()系列方法来构造线程安全的集合。为了和老版本的代码兼容,Java保留了Vector的线程安全特性。
jacktanlikejava 2009-12-20
  • 打赏
  • 举报
回复
就是因为vector是线程安全的,所以在性能上没有其他的非线程安全的集合类高,毕竟大部分的应用程序是无需关注线程安全的。所以逐渐就没有人使用了。加上Executor框架的盛行,就更加没有人注意了
super254 2009-12-20
  • 打赏
  • 举报
回复
一天不来,帖子沉得这么厉害啊,就没有对这个问题感兴趣的
sean1203 2009-12-19
  • 打赏
  • 举报
回复
public boolean contains(Object elem) {
return indexOf(elem, 0) >= 0;
}
这个无synchronized的
我觉得
可能是Observable的方法需要进行锁定排斥的
高手快来啊
sean1203 2009-12-19
  • 打赏
  • 举报
回复
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
这个并不是原子性的
不加synchronized可能会乱
sean1203 2009-12-19
  • 打赏
  • 举报
回复
我看了vector的api
发现那些方法前面没synchronized
可能你去看下vector源码可能找到答案
这问题有点难
加载更多回复(7)

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧