springboot多线程安全demo

下面例子是线程安不安全实例


import com.vip.vman.client.zk.ZkLock;
import com.vip.vman.result.BasicResult;
import com.vip.vman.service.job.ZKJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping(value = "/vman/sys2")
public class System2Controller {

    @Autowired
    ZKJob zkJob;
    private volatile  Integer value = 0;

    //这个是线程不安全的,即使变量设置了volatile
    @RequestMapping(value = "/cacheClean3", method = RequestMethod.GET)
    public  BasicResult expireRedis3(){
        BasicResult basicResult = new BasicResult<>();
        value++;
        basicResult.setSingleResult(value);
        return basicResult;
    }

    //因为加了synchronized,所以线程安全。这个只能针对单实例安全,但是多实例并也不安全
    @RequestMapping(value = "/cacheClean4", method = RequestMethod.GET)
    public synchronized BasicResult expireRedis4(){
        BasicResult basicResult = new BasicResult<>();
        //证
        value++;
        basicResult.setSingleResult(value);
        return basicResult;
    }

    @RequestMapping(value = "/cacheClean5", method = RequestMethod.GET)
    public  BasicResult expireRedis5() throws Exception {
        BasicResult basicResult = new BasicResult<>();
        ZkLock lock = new ZkLock(zkJob.getZK(), "/vman/analyse_task_delete/lock2");
        try {
            if( lock.acquire(20, TimeUnit.SECONDS) ) {
                value++;
            }
        }catch (Exception e) {
            log.info("exception:{}",e);
        }finally {
            lock.release();
        }
        basicResult.setSingleResult(value);
        return basicResult;
    }
}

你可能感兴趣的:(spring,boot,安全,java)