the field is sometimes used inside synchronized block and sometimes used without synchronization
Is it safe to use field inside and outside synchronized block?
问题:
Background
Our app sends emails which are queued in a database table. We've had some instances of duplicate emails being sent, so I'm implementing a lock to prevent multiple threads from sending emails simultaneously.
ReSharper is warning me that:
the field is sometimes used inside synchronized block and sometimes used without synchronization
Question
Why is ReSharper telling me this, and why might I be worried about it?
Code
Here's my (abridged) code:
private readonly IMailQueueRepository _mailQueueRepository = new MailQueueRepository();
private static object _messageQueueLock = new object();
public void SendAllQueuedMessages(IPrincipal caller)
{
lock (_messageQueueLock) // Prevent concurrent callers
{
var message = _mailQueueRepository.GetUnsentMessage();
while (message != null)
{
SendQueuedMessage(message);
message = _mailQueueRepository.GetUnsentMessage();
}
}
}
public void SendQueuedMessage(IMessage message)
{
// I get the ReSharper warning here on _mailQueueRepository
var messageAttachments = _mailQueueRepository.GetMessageAttachments(message.Id);
// etc.
}
解答:
Problem scenario :
We've had some instances of duplicate emails being sent, so I'm implementing a lock to prevent multiple threads from sending emails simultaneously.
So you are using Lock() to prevent this happening, that means you need to synchronize threads accessing a common resource which in this case _mailQueueRepository
But again in the same code you use _mailQueueRepository without a Lock
// I get the ReSharper warning here on _mailQueueRepository
var messageAttachments = _mailQueueRepository.GetMessageAttachments(message.Id); // <== Accessed without a lock
So it's a warning to tell that your valuable resource is accessed in two different forms : one as synchronized(thread safe) and other non-synchronized(non thread safe).
And it's a warning that let you know(or let you identify) issues that could arise from this contradictory usage of the resource _mailQueueRepository. Choice is yours to either make all usages of _mailQueueRepository synchronized (use with a lock and warning will be gone) or manage not to run for race conditions.
Additionally you might consider to re-structure the codes in such a way that your SendQueuedMessage() is called with parameters which are extracted from _mailQueueRepositoryavoiding mix usage.
Actually, it's the method which reads the queue and sends emails - not the repository itself - that I'm trying to prevent concurrent access to. I want threads to be able to write to the repository while one thread is reading emails and sending them. But I guess ReSharper can't tell that, so it warns me. I know that I'm actually fine with unsynchronized access to that resource, so I guess I'm safe to ignore the warning? – OutstandingBill
@OutstandingBill - From resharper : "Warnings In addition to compiler errors and warnings, ReSharper displays its own warnings that don't prevent your code from compiling but may nevertheless represent serious coding inefficiencies". Resharper is intelligence enough to say contradictory usage but you are the one know what actual usage is. If you are confirmed to use the resource well managed you could ignore the warning :) – KcDoD
@OutstandingBill Additionally you might be interested in re-tructuring the method to take parameters extracted from the field , rather than using it in mix context – KcDoD
the field is sometimes used inside synchronized block and sometimes used without synchronization的更多相关文章
- Java同步块(synchronized block)使用详解
Java 同步块(synchronized block)用来标记方法或者代码块是同步的.Java同步块用来避免竞争.本文介绍以下内容: Java同步关键字(synchronzied) 实例方法同步 静 ...
- JMM(java内存模型)
What is a memory model, anyway? In multiprocessorsystems, processors generally have one or more laye ...
- TBS 手册 --phpv 翻译
为何使用它? 示例 下载 手册 支持 论坛 推荐 秀出你的站点 http://phpv.net/TBS_Manual.htm#html_automatic 网站: http://www.tinybut ...
- Java Synchronized Blocks
From http://tutorials.jenkov.com/java-concurrency/synchronized.html By Jakob Jenkov A Java synchro ...
- 关于java的Synchronized,你可能需要知道这些(上)
对于使用java同学,synchronized是再熟悉不过了.synchronized是实现线程同步的基本手段,然而底层实现还是通过锁机制来保证,对于被synchronized修饰的区域每次只有一个线 ...
- strong reference cycle in block
However, because the reference is weak, the object that self points to could be deallocated while th ...
- java synchronized静态同步方法与非静态同步方法,同步语句块
摘自:http://topmanopensource.iteye.com/blog/1738178 进行多线程编程,同步控制是非常重要的,而同步控制就涉及到了锁. 对代码进行同步控制我们可以选择同步方 ...
- Java Synchronized Blocks vs. Methods
It's possible to synchronize both an entire method and a section of code within a method, and you ma ...
- Codeforces Gym 100002 C "Cricket Field" 暴力
"Cricket Field" Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/gym/1000 ...
随机推荐
- response返回随笔
response.setHeader("Content-type", "text/html;charset=UTF-8");//这句话的意思,是让浏览器用utf ...
- 1036. Boys vs Girls (25)
#include <stdio.h>#include <string.h>int main(){ int n,i; while(scanf("%d",&am ...
- poj 2774 Long Long Message 后缀数组LCP理解
题目链接 题意:给两个长度不超过1e5的字符串,问两个字符串的连续公共子串最大长度为多少? 思路:两个字符串连接之后直接后缀数组+LCP,在height中找出max同时满足一左一右即可: #inclu ...
- jquery.prompt.js 弹窗的使用
/*** * Prompt提示语插件 * 编写时间:2013年4月8号 * version:Prompt.1.0.js * author:小宇<i@windyland.com> ***/ ...
- JAVA中的各种 哈希码(HashCode) 与 equals方法在HIBERNATE的实际应用[转载]
1.什么是哈希码(HashCode) 在Java中,哈希码代表对象的特征.例如对象 Java代码 String str1 = “aa”, str1.hashCode= 3104 String str2 ...
- 详解Google-ProtoBuf中结构化数据的编码
本文的主要内容是google protobuf中序列化数据时用到的编码规则,但是,介绍具体的编码规则之前,我觉得有必要先简单介绍一下google protobuf.因此,本文首先会介绍一些google ...
- 【通信】Netty JBOSS提供的一个java开源框架
Netty是由JBOSS提供的一个java开源框架.Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可靠性的网络服务器和客户端程序dsf. 也就是说,Netty 是一个基 ...
- 通过android.provider包查看android系统定义的provider.
原先的2.2的android源码已经不是那么容易找到了,我稍稍搜索了下找到了一两个没速度的死链就失去了兴趣.不过还好忽然发现在android.provider包下包含了常见的provider的使用方法 ...
- 动态内存 this指针
#include <iostream> #include <string> class Company { public: Company(std::string theNam ...
- MVC4多语言IHttpModule实现
最近项目需要多语言环境了. 由于项目页面较多,逐个Action去读取资源文件不大现实.就想到了使用 IHttpModule配合MVC的路由规则来实现. 首先创建以个mvc4的应用程序,添加资源文件夹( ...