Java Concurrency In Practice -Chapter 2 Thread Safety
Writing thread-safe code is managing access to state and in particular to shared, mutable state.
Object's state is its data, stored in state variables such as instance or static fields.
Whether an object needs to be thread-safe depends on whether it will be accessed from multiple threads.
Synchronization includes
- Synchronized keyword
- Volatile variables
- Explicit locks
- Atomic variables
Ways to avoid inappropriate synchronization with multiple threads access.
- Don't share the state variable across threads;
- Make the state variable immutable; or
- Use synchronization whenever accessing the state variable.
Good practice on designing thread-safe classes
- Good object-oriented techniques - encapsulation(Don't expose the accessibility of the fields of the class too much).
- Immutability
- Clear specification of invariants
2.1 What is Thread Safety
A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
Thread safe classes encapsulate any needed synchronization so that clients need not provide their own.
Stateless objects are always thread-safe.
eg. It is only when servlets want to remember things from one request to another that the thread safety requirement becomes an issue.
2.2 Atomicity
Classic operation scenario
- read-modify-write: To increment a counter, you have to know its previous value and make sure no one else changes or uses that value while you are in mid‐update.
- check‐then‐act: you observe something to be true and then take action based on that observation (create X); but in fact the observation could have become invalid between the time you observed it and the time you acted on it (someone else created X in the meantime), causing a problem (unexpected exception, overwritten data, file corruption).
2.2.1 Race Conditions
A race condition occurs when the correctness of a computation depends on the relative timing or interleaving of multiple threads by the runtime.
@NotThreadSafe
public class LazyInitRace {
private ExpensiveObject instance = null;
public ExpensiveObject getInstance() {
if (instance == null)
instance = new ExpensiveObject();
return instance;
}
}
Operations A and B are atomic with respect to each other, from the perspective of a thread executing A, when another thread executes B, either all of B has executed or none of it has. An atomic operation is one that is atomic with respect to all operations, including itself, that operate on the same state.
@NotThreadSafe
public class UnsafeCountingFactorizer implements Servlet {
private long count = 0;
public long getCount() {
return count;
}
public void service(ServletRequest req, ServletResponse resp) {
BigInteger i = extractFromRequest(req);
BigInteger[] factors = factor(i);
++count;
encodeIntoResponse(resp, factors);
}
}
The java.util.concurrent.atomic package contains atomic variable classes for effecting atomic state transitions on
numbers and object references. By replacing the long counter with an AtomicLong, we ensure that all actions that
access the counter state are atomic.
@ThreadSafe
public class CountingFactorizer implements Servlet {
private final AtomicLong count = new AtomicLong(0);
public long getCount() {
return count.get();
}
public void service(ServletRequest req, ServletResponse resp) {
BigInteger i = extractFromRequest(req);
BigInteger[] factors = factor(i);
count.incrementAndGet();
encodeIntoResponse(resp, factors);
}
}
Principle
Where practical, use existing thread-safe objects, like AtomicLong, to manage your class's state. It is simpler to reason about the possible states and state transitions for existing thread-safe objects than it is for arbitrary state variables, and this makes it easier to maintain and verify thread safety.
2.3 Locking
Dealing with more than one states currency operations within one object.
Principle
To preserve state consistency, update related state variables in a single atomic operation.
2.3.1 Intrinsic Locks
A synchronized block has two parts: a reference to an object that will serve as the lock, and a block of code to be guarded by that lock. A synchronized method is shorthand for a synchronized block that spans an entire method body, and whose lock is the object on which the method is being invoked. (Static synchronized methods use the Class object for the lock.)
2.3.2 Reentrancy
Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.
When a thread acquires a previously unheld lock, the JVM records the owner and sets the acquisition count to one. If that same thread acquires the lock again, the count is incremented, and when the owning thread exits the synchronized block, the count is decremented. When the count reaches zero, the lock is released.
2.4 Guarding State with Locks
For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held.
For every invariant that involves more than one variable, all the variables involved in that invariant must be guarded by the same lock.
put-if-absent operation
if (!vector.contains(element))
vector.add(element);
2.5 Liveness and Performance

Refined solution for concurrent operation on more than on state object inside the Class instance
@ThreadSafe
public class CachedFactorizer implements Servlet {
@GuardedBy("this")
private BigInteger lastNumber;
@GuardedBy("this")
private BigInteger[] lastFactors;
@GuardedBy("this")
private long hits;
@GuardedBy("this")
private long cacheHits;
public synchronized long getHits() {
return hits;
}
public synchronized double getCacheHitRatio() {
return (double) cacheHits / (double) hits;
}
public void service(ServletRequest req, ServletResponse resp) {
BigInteger i = extractFromRequest(req);
BigInteger[] factors = null;
synchronized (this) {
++hits;
if (i.equals(lastNumber)) {
++cacheHits;
factors = lastFactors.clone();
}
}
if (factors == null) {
factors = factor(i);
synchronized (this) {
lastNumber = i;
lastFactors = factors.clone();
}
}
encodeIntoResponse(resp, factors);
}
}
Principle
- There is frequently a tension between simplicity and performance. When implementing a synchronization policy, resist the temptation to prematurely sacrifice simplicity (potentially compromising safety) for the sake of performance.
- Avoid holding locks during lengthy computations or operations at risk of not completing quickly such as network or console I/O.
Java Concurrency In Practice -Chapter 2 Thread Safety的更多相关文章
- Java Concurrency In Practice - Chapter 1 Introduction
1.1. A (Very) Brief History of Concurrency motivating factors for multiple programs to execute simul ...
- Java Concurrency in Practice 读书笔记 第十章
粗略看完<Java Concurrency in Practice>这部书,确实是多线程/并发编程的一本好书.里面对各种并发的技术解释得比较透彻,虽然是面向Java的,但很多概念在其他语言 ...
- Java Concurrency in Practice——读书笔记
Thread Safety线程安全 线程安全编码的核心,就是管理对状态(state)的访问,尤其是对(共享shared.可变mutable)状态的访问. shared:指可以被多个线程访问的变量 mu ...
- Java Concurrency In Practice
线程安全 定义 A class is thread-safe if it behaves correctly when accessed from multiple threads, regardle ...
- 读Java Concurrency in Practice. 第六章.
这一章开讲任务执行.绝大多数并发程序的工作都可以分解为抽象的.互不相关的工作单元,称之为任务(Task). 使用java线程来执行任务 以web服务器的实现举例, 此时将用户的一次连接,当做一个独立的 ...
- java并发编程实战(java concurrency in practice)
第一章 线程共享进程范围内的资源,但每个线程都有各自的程序计数器.栈以及局部变量等. 多个线程可以同时调度到多个CPU上运行. 线程的优势? 在服务应用程序中,可以提升资源利用率以及系统吞吐率 ...
- java concurrency in practice读书笔记---ThreadLocal原理
ThreadLocal这个类很强大,用处十分广泛,可以解决多线程之间共享变量问题,那么ThreadLocal的原理是什么样呢?源代码最能说明问题! public class ThreadLocal&l ...
- Java Concurrency in Practice 读书笔记 第二章
第二章的思维导图(代码迟点补上):
- 深入浅出 Java Concurrency (4): 原子操作 part 3 指令重排序与happens-before法则
转: http://www.blogjava.net/xylz/archive/2010/07/03/325168.html 在这个小结里面重点讨论原子操作的原理和设计思想. 由于在下一个章节中会谈到 ...
随机推荐
- WebGL 3D on iOS8 正式版
今天iOS8终于正式发布了,升级了手头设备后对我来说最重要的就是测试WebGL的3D是否真的能跑苹果的系统了,跑了多个HT for Web的3D例子都非常流畅,比Android刚支持WebGL时好太多 ...
- 极简Unity调用Android方法
简介 之前写了篇unity和Android交互的教程,由于代码里面有些公司的代码,导致很多网友看不懂,并且确实有点小复杂,这里弄一个极简的版本 步骤 废话不多说,直接来步骤吧 1.创建工程,弄大概像这 ...
- jquery实现智能表单
现在很多网站的注册模块都可以实现即时检查格式是否正确,这样极大的增强了用户体验,对开发非常有利. 下面的代码是利用jquery实现了对一个表单字段格式的即时检查(包括字段长度.邮箱格式),同时在提交时 ...
- .NET开发 正则表达式中的 Bug
又发现了一个 .net 的 bug!最近在使用正则表达式的时候发现:在忽略大小写的时候,匹配值从 0xff 到 0xffff 之间的所有字符,正则表达式竟然也能匹配两个 ASCII 字符:i(code ...
- AxWebBrowser与WebBrowserU盾登陆时的使用
PS:上个月为财务小妹做了个自动上传报表的工具,财务妹子表示调戏我很开心T_T~~. 由于该小程序涉及到登陆,准备用WebBroswer,这一下撞墙上了,无法展示U盾密码框. 我在博问上的问题 ...
- 分享AceAdminUI后台框架-你喜欢吗?
距离上次写文章也很久了,这次分享一下自己刚刚看上的一款UI框架(自己买的),国外货,提供下载 第100位评论的我将会送出一个小礼物 礼物链接:http://yanghenglian.taobao.co ...
- mysql学习笔记 第九天
order by ,limit 和where子查询的使用 order by: order by 列名1,[列名2],[列名3]...(结果先按列1进行排序,在列1的相同的情况下,再按照列2的排序,以此 ...
- 通过代码的方式完成WCF服务的寄宿工作
使用纯代码的方式进行服务寄宿 服务寄宿的目的是为了开启一个进程,为WCF服务提供一个运行的环境.通过为服务添加一个或者多个终结点,使之暴露给潜在的服务消费,服务消费者通过匹配的终结点对该服务进行调用, ...
- Linux修改命令提示符(关于环境参量PS1)
关乎环境参量的四个文件/etc/profile /etc/bashrc ~/.bashrc ~/.bash_profile $$$:/etc/profile:此文件为系统的每个用户设置环境信息,当 ...
- winform(公共控件)
一.客户端设计思路 1.理顺设计思路,架构框架 2.设计界面 3.编写后台代码 4.数据库访问 二.公共控件 1.Button(按钮): ⑴ Enabled :确定是否启用控件 ⑵ Visible:确 ...