2

我在一次采访中被问到以下问题。

有一个对象被多个线程共享。该对象具有以下功能。你如何确保不同的线程可以同时为不同的参数 x 值执行函数?如果两个线程以相同的 x 值执行,则其中一个线程应该被阻塞。

public void func(String x){
-----
}  

“synchronized”关键字在这种情况下不起作用,因为它会确保一次只能执行一个线程。请让我知道这将是什么解决方案

4

3 回答 3

6

首先想到的是

public void func(String x){
    synchronized (x.intern()) {
        // Body here
    }
}  

这将像描述的那样运行;当然,这感觉像是一种讨厌的 hack,因为正在同步的对象是公开可访问的,因此其他代码可能会干扰锁定。

于 2013-02-21T05:44:24.080 回答
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(); 
}
于 2013-02-21T05:47:55.990 回答
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;
    }
}

请注意,它可以通过简单的映射和全局锁以更简单的方式实现。但是,我想避免全局锁,以提高吞吐量。

于 2013-02-21T06:01:40.867 回答