http://stackoverflow.com/questions/28715625/is-it-safe-to-use-field-inside-and-outside-synchronized-block

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的更多相关文章

  1. Java同步块(synchronized block)使用详解

    Java 同步块(synchronized block)用来标记方法或者代码块是同步的.Java同步块用来避免竞争.本文介绍以下内容: Java同步关键字(synchronzied) 实例方法同步 静 ...

  2. JMM(java内存模型)

    What is a memory model, anyway? In multiprocessorsystems, processors generally have one or more laye ...

  3. TBS 手册 --phpv 翻译

    为何使用它? 示例 下载 手册 支持 论坛 推荐 秀出你的站点 http://phpv.net/TBS_Manual.htm#html_automatic 网站: http://www.tinybut ...

  4. Java Synchronized Blocks

    From http://tutorials.jenkov.com/java-concurrency/synchronized.html By Jakob Jenkov   A Java synchro ...

  5. 关于java的Synchronized,你可能需要知道这些(上)

    对于使用java同学,synchronized是再熟悉不过了.synchronized是实现线程同步的基本手段,然而底层实现还是通过锁机制来保证,对于被synchronized修饰的区域每次只有一个线 ...

  6. strong reference cycle in block

    However, because the reference is weak, the object that self points to could be deallocated while th ...

  7. java synchronized静态同步方法与非静态同步方法,同步语句块

    摘自:http://topmanopensource.iteye.com/blog/1738178 进行多线程编程,同步控制是非常重要的,而同步控制就涉及到了锁. 对代码进行同步控制我们可以选择同步方 ...

  8. 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 ...

  9. Codeforces Gym 100002 C "Cricket Field" 暴力

    "Cricket Field" Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/gym/1000 ...

随机推荐

  1. ecshop中无限处理分类

    数据库表记录结构 <?php $sql = "SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, ...

  2. 使用GruntJS构建Web程序

    Gruntjs是JavaScript项目的构建工具,也是基于node的一个命令行工具.很多开源JS项目都是使用它搭建.如jQuery.Qunit.CanJS等.它有以下作用 合并JS文件 压缩JS文件 ...

  3. ENVI栅格文件增强后将LUT保存完输出img图像进行分类

    ENVI栅格文件储存 图像原始的DN(Digital Number)值记录图像的光谱信息,不能轻易更改。在窗口中显示的一般是经过拉伸等增强处理的LUT上的灰度值,在保存文件时,就有不同的方式。 1.  ...

  4. Ubuntu下Sublime Text 3无法输入中文的解决方案

    1. 保存下面的代码到文件sublime_imfix.c中: /* * sublime-imfix.c * Use LD_PRELOAD to interpose some function to f ...

  5. sysfs接口函数到建立_DEVICE_ATTR

    sysfs接口函数到建立_DEVICE_ATTR 最近在弄Sensor驱动,看过一个某厂家的成品驱动,里面实现的全都是sysfs接口,hal层利用sysfs生成的接口,对Sensor进行操作. 说道s ...

  6. ios NavBar+TarBar技巧

    NavBar+TarBar iphone开发 NavBar+TarBar 1  改变NavBar颜色:选中Navigation Bar 的Tint属性.选中颜色. 2  隐藏“back”按钮: sel ...

  7. 【BZOJ 2654】tree

    Description 给你一个无向带权连通图,每条边是黑色或白色.让你求一棵最小权的恰好有need条白色边的生成树. 题目保证有解. Input 第一行V,E,need分别表示点数,边数和需要的白色 ...

  8. python字符串截取与替换的例子

    python字符串截取与替换的多种方法 时间:2016-03-12 20:08:14来源:网络 导读:python字符串截取与替换的多种方法,以冒号分隔的字符串的截取方法,python字符串替换方法, ...

  9. 2733: [HNOI2012]永无乡 - BZOJ

    Description 永无乡包含 n 座岛,编号从 1 到 n,每座岛都有自己的独一无二的重要度,按照重要度可 以将这 n 座岛排名,名次用 1 到 n 来表示.某些岛之间由巨大的桥连接,通过桥可以 ...

  10. js根据id、pid把数据转为树结构

    //格式化树数据 function toTreeData(data) { var pos = {}; var tree = []; var i = 0; while (data.length != 0 ...