也许这是一个非常愚蠢的问题,但请听我说。 我有一个用例,我得到许多并发请求,为特定的输入日期做某事。 如果在同一输入日期收到两个并发请求,则后续请求不应继续,直到先前请求完全完成(有充分理由)。 使用标准java.util.concurrent组件实现此目的的最佳方法是什么? 我最初的想法是有一个LockFactory,它会销售锁并保留一份副本,以表明它正在使用中,后续请求将等待()。 然而,这似乎有很多锅炉板代码 - 任何更简单的技巧,是在逃避我?
提前致谢!
Maybe this is a really dumb question, but please hear me out. I have a use case where I get many concurrent requests to do something for a particular input date. If there are two concurrent requests received for the same input date, the subsequent request should not proceed till the prior request has finished completely (for good reasons). What is the best way to use standard java.util.concurrent components to achieve this? My initial thoughts were around having a LockFactory which will vend locks and keep a copy to indicate that it is in use and on which the subsequent request will await(). However, this seems to have lot of boiler-plate code - any simpler trick that is eluding me?
Thanks in advance!
最满意答案
您可以在日期的时间散列单个锁。
private static final ConcurrentMap<Long,Lock> dateLock = new ConcurrentHashMap<Long,Lock>(); public static Lock getLock(Date date){ Lock lock = dateLock.get(date.getTime()); if(lock == null){ Lock lock = new ReentrantLock(); Lock temp =dateLock.putIfAbsent(lock); lock = temp == null ? lock : temp; } return lock; }如果您需要同一天,而不一定是确切的日期(以毫秒为单位),您可以执行类似的操作
private static final ConcurrentMap<String,Lock> dateLock = new ConcurrentHashMap<String,Lock>(); public static Lock getLock(Date date){ String formattedDate = new SimpleDateFormat("MM\dd\yyyy").parse(date); Lock lock = dateLock.get(formattedDate); if(lock == null){ Lock lock = new ReentrantLock(); Lock temp =dateLock.putIfAbsent(lock); lock = temp == null ? lock : temp; } return lock; }然后任何需要在日期互斥的请求
Date date = ...; Lock lock = getLock(date); lock.lock();等等
You can hash individual locks on the date's time.
private static final ConcurrentMap<Long,Lock> dateLock = new ConcurrentHashMap<Long,Lock>(); public static Lock getLock(Date date){ Lock lock = dateLock.get(date.getTime()); if(lock == null){ Lock lock = new ReentrantLock(); Lock temp =dateLock.putIfAbsent(lock); lock = temp == null ? lock : temp; } return lock; }If you need the same day and not necessarily the exact date in milliseconds you can do something like
private static final ConcurrentMap<String,Lock> dateLock = new ConcurrentHashMap<String,Lock>(); public static Lock getLock(Date date){ String formattedDate = new SimpleDateFormat("MM\dd\yyyy").parse(date); Lock lock = dateLock.get(formattedDate); if(lock == null){ Lock lock = new ReentrantLock(); Lock temp =dateLock.putIfAbsent(lock); lock = temp == null ? lock : temp; } return lock; }Then any request that needs mutual exclusion on a date
Date date = ...; Lock lock = getLock(date); lock.lock();and so forth
更多推荐
发布评论