做活动,要发优惠券,规定一人只能领取一次(一张)。一天下来发现有一个客户领到了4张,且是同一秒生成的,源代码如下:
估计多个线程同时进了add方法。
想到了单例的双重校验,现修改代码如下,
public Object activityTicketAdd(String token,String activityName) { Customer customer = getCustomer(token) ; Ticket ticket = new Ticket(); ticket.setCustomerId(customer.getId()); ticket.setFrom(activityName); if(ticketsDao.queryList(ticket,null,null).size()<=0) { synchronized (this) { if (ticketsDao.queryList(ticket, null, null).size() <= 0) { return ticketService.addTicket(customer, activityName); } } } return "REPEAT"; }
参考(单例模式中的双重校验锁):https://www.cnblogs.com/diaoniwa/p/7299746.html
同时查看synchronized(this/class) 的区别:https://www.cnblogs.com/huansky/p/8869888.html