简体   繁体   中英

Read and Write lock

I have a simple web-app in which I use struts and xslt transformation. In action class I try to call method "save" if I get correct data

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();
        }
    }
        ...
}

But I have one question. My teacher says that best place for lock-s is action class or command ( in case simple web-app)

but In saveProducts method I do transformation before writing new data in xml file. It means that I lose control on reading correct data if use just writeLock in action-class.

I XMLProductDAO I have smth like this

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();
    }
    // /.....
}

can i get faced with writing incorrect data in xml if will use just writeLock in action class?

So, of course you CAN always write incorrect code that uses a write lock. However, when it comes to protecting data using locks if you only use write locks (and you use them in all appropriate locations) then your data will be safe. This would result in the same performance as using a synchronized block. You get improved performance when you use read locks where appropriate but adding the use of read locks adds a potential for bugs if you attempt to write data in an area that only has a read lock. So, only write locks equals more safety but less performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM