我在接受采访时被问到以下问题。
有一个对象由多个线程共享。该对象具有以下功能。如何确保不同的线程可以同时为参数x的不同值执行这些功能?如果两个线程正在以相同的x值执行,则应阻止其中一个。
public void func(String x){
-----
}
“synchronized”关键字在这种情况下不起作用,因为它将确保一次只能执行一个线程。请告诉我这个
的解决方案答案 0 :(得分:6)
首先想到的是像
public void func(String x){
synchronized (x.intern()) {
// Body here
}
}
这将表现得如上所述;当然,这感觉就像一个讨厌的黑客,因为被同步的对象是公共可访问的,而其他代码可能会因此而干扰锁定。
答案 1 :(得分:0)
将HashMap创建为成员变量。
private HashMap<String,Lock> lockMap = new HashMap<String,Lock>();
public void func(String x){
if(lockMap.get(x) == null){
lockMap.put(x,new ReentrantLock());
}
lockMap.get(x).lock();
...
...
lockMap.get(x).unlock();
}
答案 2 :(得分:0)
可能面试官对Ernest Friedman-Hill提出的解决方案感兴趣。但是,由于它的缺点,它通常不能用于生产代码。一旦我编写了以下同步实用程序来处理此问题:
package com.paypal.risk.ars.dss.framework.concurrent;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
public class MultiLock <K>{
private ConcurrentHashMap<K, ReentrantLock> locks = new ConcurrentHashMap<K, ReentrantLock>();
/**
* Locks on a given id.
* Make sure to call unlock() afterwards, otherwise serious bugs may occur.
* It is strongly recommended to use try{ }finally{} in order to guarantee this.
* Note that the lock is re-entrant.
* @param id The id to lock on
*/
public void lock(K id) {
while (true) {
ReentrantLock lock = getLockFor(id);
lock.lock();
if (locks.get(id) == lock)
return;
else // means that the lock has been removed from the map by another thread, so it is not safe to
// continue with the one we have, and we must retry.
// without this, another thread may create a new lock for the same id, and then work on it.
lock.unlock();
}
}
/**
* Unlocks on a given id.
* If the lock is not currently held, an exception is thrown.
*
* @param id The id to unlock
* @throws IllegalMonitorStateException in case that the thread doesn't hold the lock
*/
public void unlock(K id) {
ReentrantLock lock = locks.get(id);
if (lock == null || !lock.isHeldByCurrentThread())
throw new IllegalMonitorStateException("Lock for " + id + " is not owned by the current thread!");
locks.remove(id);
lock.unlock();
}
private ReentrantLock getLockFor(K id) {
ReentrantLock lock = locks.get(id);
if (lock == null) {
lock = new ReentrantLock();
ReentrantLock prevLock = locks.putIfAbsent(id, lock);
if (prevLock != null)
lock = prevLock;
}
return lock;
}
}
请注意,它可以通过简单的地图和全局锁以更简单的方式实现。但是,我想避免全局锁定,以提高吞吐量。