我有一个简单的web-app,其中我使用了struts和xslt转换。在action类中,如果我得到正确的数据,我会尝试调用方法"save“。
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
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中写入错误数据的问题吗?
发布于 2012-10-04 01:54:07
所以,当然你可以使用写锁来编写不正确的代码。但是,当使用锁保护数据时,如果只使用写锁(并且在所有适当的位置使用它们),那么您的数据将是安全的。这将产生与使用synchronized块相同的性能。在适当的情况下使用读锁可以提高性能,但是如果您试图在只有读锁的区域中写入数据,则添加读锁的使用会增加潜在的but。因此,只有写锁等于更高的安全性但更低的性能。
https://stackoverflow.com/questions/12712864
复制相似问题