即对类似如下的方法
public synchronized void sync() {
a();
//其实只有b需要同步处理
b();
c();
}
改进为
public void sync() {
a();
synchronized (this){
b();
}
c();
}
从而减少锁的持有时间
如ConcurrentHashMap内部分成若干个小的HashMap,每个HashMap加不同的锁
即通过读写锁,实现读读的时候不阻塞,只在写写和读写时阻塞。相比与减少锁粒度是通过分割数据实现,读写锁是通过对系统功能的分割实现。
锁分离可以说是对读写锁的一种延伸,因为他也是通过系统功能的分割实现。如LinkedBlockingQueue,他的take()和put()方法分别作用于队列的前端和尾端,因此互不影响,所以take()和put()方法可以各自用不同的锁
如果对同一个锁不停的请求和释放,对性能是有害的。所以JVM会把一些锁操作整合成一个锁操作如:
把
public void sync(lock) {
synchronized (lock){
//do sth
}
synchronized (lock){
//do sth
}
}
变为
public void sync(lock) {
synchronized (lock){
//do sth
//do sth
}
}
把
for(int i = 0;i<size;i++){
synchronized (lock){
//do sth
}
}
变为
synchronized(lock){
for(int i = 0;i<size;i++){
//do sth
}
}
针对几乎没有锁竞争的场合,如果一个线程开启了锁,大概率下次还是这个线程使用这个锁,因此可以对锁对象的对象头添加该线程的id,这样一来再次请求锁时,如果是同一个id,就无续任何同步操作。从而节省了大量有关锁的操作。JVM通过参数:-XX:+UseBiasedLocking
当一个线程没能获得锁时,JVM不会马上把线程挂起,而是让该线程做几次空循环,即做自旋。如果经过几次自旋后,获得了锁,就不对其挂起。如果还是不能获得锁,才挂起,从而通过减少挂起次数,挺高运行效率。
JVM在编译时会对上下文进行扫描,去除不可能存在竞争的锁。如:
public String[] createString(){
Vector<String> v = new Vector<>();
for(int i = 0;i<1000;i++){
v.add(Integer.toString(i));
}
return v.toArray(new String[]{});
}
这里的v只是一个局部变量,因此Vector的内部所有加锁操作都是没必要的,会被去除掉
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
如果我们使用的是线程池,当任务结束后,线程未必退出,所以保险起见,就好通过ThreadLocal.remove()将这个变量手动移除
CAS即比较交换技术,他包含三个参数:CAS(V,E,N)。V表示要更新的变量,E表示预期值,N表示新值。只有在V的值等于E的值时,V的值才会设置成N,如AtomicInteger的getAndDecrement方法:
public final int getAndDecrement() {
for(;;){
int current = get();
int next = current+1;
if(compareAndSet(current, next)){
return next;
}
}
}
其中compareAndSet是通过Unsafe类实现
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
compareAndSwapInt是一个native方法,通过指针实现,valueOffset为对象内的偏移量。通过valueOffset是否一致,可以知道对象是否被修改。
需要关注的是Unsafe属于JDK的内部使用专属类,即和rt.jar一样由Bootstrap加载,而不是通过AppLoader加载。因此无法通过反射加载他。同时他不可以被继承(final对象)和自己new出来(private构造方法)如下面代码所示。
package sun.misc;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
import sun.misc.VM;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
public final class Unsafe {
//省略代码
private Unsafe() {
}
//省略代码
}
因为Unsafe涉及到对指针的使用,而指针是不安全的,因此java开发者不希望我们直接使用Unsafe类。
以下的无锁类都通过cas实现,从而在保证支持线程安全的同时,提高了并发的运行效率。
常见用法:
static AtomicInteger atomicInteger = new AtomicInteger();
static ExecutorService exe = Executors.newFixedThreadPool(10);
static final CountDownLatch countDownLatch = new CountDownLatch(100);
static int j =0;
public static class AddThread implements Runnable{
@Override
public void run() {
for(int i=0;i<1000;i++){
j++;
atomicInteger.incrementAndGet();
}
countDownLatch.countDown();
}
}
public static void main(String[] args) throws Exception{
for(int i = 0 ;i<100;i++){
exe.submit(new AddThread());
}
countDownLatch.await();
System.out.println(atomicInteger.get());
System.out.println(j);
}
此时atomicInteger会是10000而j是一个比100000小的数
可以对一般的对象进行封装,使其也可以通过cas操作,达到线程安全的目的。
常见用法:
public class TestModel {
private int i = 0;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
public class Test1 {
static AtomicReference<TestModel> atomicInteger = new AtomicReference<>();
static ExecutorService exe = Executors.newFixedThreadPool(10);
static final CountDownLatch countDownLatch = new CountDownLatch(100);
public static class AddThread implements Runnable{
@Override
public void run() {
for(int i=0;i<1000;i++){
while (true){
TestModel current = atomicInteger.get();
TestModel next = new TestModel();
next.setI(current.getI()+1);
if(atomicInteger.compareAndSet(current,next)){
break;
}
}
}
countDownLatch.countDown();
}
}
public static void main(String[] args) throws Exception{
atomicInteger.set(new TestModel());
for(int i = 0 ;i<100;i++){
exe.submit(new AddThread());
}
countDownLatch.await();
System.out.println(atomicInteger.get().getI());
}
}
AtomicReference有一个问题,就是无法处理如:假如有一个业务是,一个人的账号少于20元,就为他充值10元,有且只能充值一次的情况。如这时他的余额是19元,系统充值后为29元,他消费10元后为19元,系统就又会为他充值。因此AtomicStampedReference在AtomicReference的基础上增加了时间戳参数stamp,每次修改对象就把stamp加1,来记录对象是不是被修改过。
使用伪代码如下:
static AtomicStampedReference<TestModel> atomicInteger = new AtomicStampedReference<>();
int stamp = atomicInteger.getStamp();
TestModel current = atomicInteger.getReference();
TestModel next = new TestModel();
next.setI(current.getI()+10);
atomicInteger.compareAndSet(current,next,stamp,stamp+1);
除了对对象进行cas封装外,还可以对数组进行封装如AtomicIntegerArray,AtomicLongArrary,AtomicReferenceArrary,主要需要关注的方法是compareAndSet(),如AtomicIntegerArray的compareAndSet方法:
//i为数组元素下标,其他与AtomicInteger一致
public final boolean compareAndSet(int i, int expect, int update)
AtomicFieldUpdater可以为一些普通变量也实现cas功能,从而方便修改因为一开始没设计好,后来发现一些变量有线程安全问题的情况。他有AtomicIntegerFieldUpdater,AtomicLongFieldUpdater,AtomicReferenceFieldUpdater使用代码示例:
public class TestUpdater {
volatile int i = 0;
}
public class Test2 {
static AtomicIntegerFieldUpdater<TestUpdater> atomicInteger = AtomicIntegerFieldUpdater.newUpdater(TestUpdater.class,"i");
static TestUpdater testUpdater = new TestUpdater();
static ExecutorService exe = Executors.newFixedThreadPool(10);
static final CountDownLatch countDownLatch = new CountDownLatch(100);
public static class AddThread implements Runnable{
@Override
public void run() {
for(int i=0;i<1000;i++){
atomicInteger.incrementAndGet(testUpdater);
}
countDownLatch.countDown();
}
}
public static void main(String[] args) throws Exception{
for(int i = 0 ;i<100;i++){
exe.submit(new Test2.AddThread());
}
countDownLatch.await();
System.out.println(testUpdater.i);
}
}
使用注意事项: