首页
学习
活动
专区
圈层
工具
发布

读写锁
EN

Stack Overflow用户
提问于 2012-10-04 00:33:08
回答 1查看 373关注 0票数 3

我有一个简单的web-app,其中我使用了struts和xslt转换。在action类中,如果我得到正确的数据,我会尝试调用方法"save“。

代码语言:javascript
复制
public ActionForward saveProduct(ActionMapping mapping, ActionForm form, 
        HttpServletRequest request, HttpServletResponse response) throws XMLProductDAOException {
    // Validation
    if (sizeValidationErrorList == 0) {
        try {
            writeLock.lock();
            productDAO.saveProducts(document, product, categoryId, subcategoryId);
        } finally {
            writeLock.unlock();
        }
    }
        ...
}

但我有一个问题。我的老师说最适合使用lock-s的地方是action class或者command (如果是简单的web-app)

但在saveProducts方法中,我会在将新数据写入xml文件之前进行转换。这意味着如果在操作类中只使用writeLock,我就会失去对读取正确数据的控制。

I XMLProductDAO我有这样的smth

代码语言:javascript
复制
public void saveProducts(Document document, Product product, Integer categoryId, Integer subcategoryId) throws XMLProductDAOException {
    // /......
    XSLTTransformer xsltTransformer = XSLTTransformer.getInstance();

    Transformer transformer = xsltTransformer.getCachedTransformer(NEW_PRODUCT_REAL_XSL_PATH);

    transformer.setParameter(PARAM_CURRENT_CATEGORY, currentCategory);
    transformer.setParameter(PARAM_CURRENT_SUBCATEGORY, currentSubcategory);
    transformer.setParameter(PARAM_PRODUCT, product);

    Writer result = new StringWriter();

    xsltTransformer.transform(transformer, result);

    File originalXML = new File(PRODUCT_REAL_XML_PATH);
    Writer fileWriter = null;
    try {
        fileWriter = new PrintWriter(originalXML, ENCODING);
        fileWriter.write(result.toString());
    } catch (IOException e) {
        logger.error(IO_EXCEPTION, e);
        throw new XMLProductDAOException(IO_EXCEPTION, e);
    } finally {
        fileWriter.close();
    }
    // /.....
}

如果在操作类中只使用writeLock,我会面临在xml中写入错误数据的问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-04 01:54:07

所以,当然你可以使用写锁来编写不正确的代码。但是,当使用锁保护数据时,如果只使用写锁(并且在所有适当的位置使用它们),那么您的数据将是安全的。这将产生与使用synchronized块相同的性能。在适当的情况下使用读锁可以提高性能,但是如果您试图在只有读锁的区域中写入数据,则添加读锁的使用会增加潜在的but。因此,只有写锁等于更高的安全性但更低的性能。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12712864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档