5

我正在尝试从数据库同步硬盘上的文件兑现。

我正在检查文件是否存在,如果不存在,我从数据库中获取文件并部署它。由于竞争条件,我不想多次写入文件。

这是我制作的代码:

重要提示:这段代码在一个 Bean 里面,它的所有含义

@Override
public String getThumbnailPictureUrl(Design design) {
    String relativePath = String.format(THUMBNAIL_URL, design.getId(), design.getThumbnailPicture().getFileName());
    String realPath = servletContext.getRealPath("/"+relativePath); 
    logger.info("Request Thumbnail picture for design: " + design.getId());
    logger.info("Thumbnail picture relative path: " + relativePath);
    logger.info("Thumbnail picture real path: " + realPath);        
    File file = new File(realPath);
    if(!file.exists()) 
    {
        synchronized (thumbnailLock) 
        {
            if(!file.exists()) 
            {
            logger.warn("Could not fild file in path: " + realPath);
            FileAttachment pictureAttachment = design.getThumbnailPicture();
            Hibernate.initialize(pictureAttachment.getAttachment());
            Data data = (Data) pictureAttachment.getAttachment();
            file = toolBox.convertBlobToFile(data.getBlob(), file);
            logger.warn("file created in path: " + realPath);
            }
        }
    }
    return relativePath;
}

有了这个解决方案,如果我找不到文件,我真的不会像任何其他文件一样写入文件 2 次,因为我正在为所有试图访问它的线程同步整个块,即使是写入不同的文件。

有什么建议么?

谢谢。

4

2 回答 2

5

类似于@Avi 的解决方案,但使用 ConcurrentHashMap。

private final ConcurrentMap<String, Object> map = new ConcurrentHashMap<>();

String name = file.getName();
Object lock = map.get(name);
if (lock == null) {
    map.putIfAbsent(name, new Object());
    lock = map.get(name);
}

synchronized (lock) {
    // do something
}

map.remove(name); 
于 2013-07-09T23:44:09.723 回答
1

创建一个HashMap锁怎么样?键将是文件路径,值将只是用作锁定的对象。假设这张地图是这样定义的:

Map<String, Object> locks = new Map<String, Object>();

这就是用途:

if(!file.exists()) 
{
    Object lock = null;
    synchronized (locks) {
       lock = locks.get(file.getName());
       if(lock == null) {
            lock = new Object();
            locks.put(file.getName(), lock);

       }
    }
    synchronized (lock) 
    {
        if(!file.exists()) 
        {
        logger.warn("Could not fild file in path: " + realPath);
        FileAttachment pictureAttachment = design.getThumbnailPicture();
        Hibernate.initialize(pictureAttachment.getAttachment());
        Data data = (Data) pictureAttachment.getAttachment();
        file = toolBox.convertBlobToFile(data.getBlob(), file);
        logger.warn("file created in path: " + realPath);
        }
    }
    synchronized(locks) { 
         map.remove(lock)); 
    }
}
于 2013-07-09T23:15:11.957 回答