Alfresco JavaScript/Rhino 多线程处理和并发

Alfresco JavaScript/Rhino multi-thread processing and concurrency

让我们考虑两个单独的 Alfresco Rhino-JavaScript 任务竞争创建同一个文件夹:

var shared = companyhome.childByNamePath("shared");
var newFolderName = "folder-x";
var newFolder = shared.childByNamePath(newFolderName);
if (newFolder==null) {
    java.lang.Thread.sleep(10000);//remove this line in second thread
    newFolder = shared.createFolder(newFolderName);
    if (newFolder==null){
        logger.error("error: "+newFolderName);
    } else {
        logger.info("success: "+newFolderName);
    }
} else {
    logger.info("already exists: "+newFolderName);
}

如果我们 运行 第一个脚本有睡眠(10 秒)而第二个脚本没有睡眠那么:

让我们想象一下有很多相互竞争的线程试图创建随机文件夹。 是否有信号量或原子操作之类的东西只阻止创建指定的文件夹(对其他文件夹不阻塞)?

抱歉,我明白了,这是微不足道的...

方法 createFolder() 是原子的,如果文件夹已经创建,我们只需要处理异常:

var getOrCreateFolder = function(parent, newFolderName){
    var newFolder = parent.childByNamePath(newFolderName);
    if (newFolder==null) {
        try {
            java.lang.Thread.sleep(10000);//remove this line in second thread
            newFolder = parent.createFolder(newFolderName);
            return {folder:newFolder,isNew:true};

        } catch (e) {
            newFolder = parent.childByNamePath(newFolderName);
            if (newFolder!=null){
                return {folder:newFolder,isNew:false};
            } else {
                throw e;
            }
        }
    } else {
        return {folder:newFolder,isNew:false};
    }
};

var shared = companyhome.childByNamePath("shared");
var newFolderName = "folder-x";
var folderDto = getOrCreateFolder(shared,newFolderName);
if (folderDto.folder==null) {
    logger.error("error: "+newFolderName);
} else {
    logger.info("done: "+newFolderName+", new: "+folderDto.isNew);
}