问题1.StringBuffer 和StringBuilder的区别
答:线程安全问题,StringBuffer线程安全,StringBuilder线程不安全
问题2.StringBuffer怎么实现线程安全
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
答:通过synchronized关键字
问题3.HashMap是线程安全的么?怎么实现线程安全
答:hashMap是线程不安全的,可以同Collections工具类的synchronizedCollection
方法实现线程安全
问题4.synchronizedCollection怎么实现HashMap线程安全?
Collections定义了一个内部类SynchronizedCollection
SynchronizedCollection实现了Collection接口,通过装饰者模式
对传入的Collection子类进行包装加锁
static class SynchronizedCollectionimplements Collection, Serializable {
private static final long serialVersionUID =3053995032091335093L;
final Collectionc;// Backing Collection
final Objectmutex;// Object on which to synchronize
SynchronizedCollection(Collection c) {
this.c = Objects.requireNonNull(c);
mutex =this;
}
SynchronizedCollection(Collection c, Object mutex) {
this.c = Objects.requireNonNull(c);
this.mutex = Objects.requireNonNull(mutex);
}
public int size() {
synchronized (mutex) {return c.size();}
}
public boolean isEmpty() {
synchronized (mutex) {return c.isEmpty();}
}
public boolean contains(Object o) {
synchronized (mutex) {return c.contains(o);}
}
public Object[] toArray() {
synchronized (mutex) {return c.toArray();}
}
public T[] toArray(T[] a) {
synchronized (mutex) {return c.toArray(a);}
}
public Iterator iterator() {
return c.iterator();// Must be manually synched by user!
}
public boolean add(E e) {
synchronized (mutex) {return c.add(e);}
}
public boolean remove(Object o) {
synchronized (mutex) {return c.remove(o);}
}
public boolean containsAll(Collection coll) {
synchronized (mutex) {return c.containsAll(coll);}
}
public boolean addAll(Collection coll) {
synchronized (mutex) {return c.addAll(coll);}
}
public boolean removeAll(Collection coll) {
synchronized (mutex) {return c.removeAll(coll);}
}
public boolean retainAll(Collection coll) {
synchronized (mutex) {return c.retainAll(coll);}
}
public void clear() {
synchronized (mutex) {c.clear();}
}
public String toString() {
synchronized (mutex) {return c.toString();}
}
// Override default methods in Collection
@Override
public void forEach(Consumer consumer) {
synchronized (mutex) {c.forEach(consumer);}
}
@Override
public boolean removeIf(Predicate filter) {
synchronized (mutex) {return c.removeIf(filter);}
}
@Override
public Spliterator spliterator() {
return c.spliterator();// Must be manually synched by user!
}
@Override
public Stream stream() {
return c.stream();// Must be manually synched by user!
}
@Override
public Stream parallelStream() {
return c.parallelStream();// Must be manually synched by user!
}
private void writeObject(ObjectOutputStream s)throws IOException {
synchronized (mutex) {s.defaultWriteObject();}
}
}
网友评论