Chapter 4. Composing Objects

本文探讨了设计线程安全类的基本要素,包括确定对象状态、维护不变量及同步策略。通过恰当的封装确保线程安全性,并介绍如何使用不可变性、线程限制和锁定来协调对对象状态的访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

Chapter 4. Composing Objects

So far, we've covered the lowlevel basics of thread safety and synchronization. But we don't want to have to analyze each memory access to ensure that our program is threadsafe; we want to be able to take threadsafe components and safely compose them into larger components or programs. This chapter covers patterns for structuring classes that can make it easier to make them threadsafe and to maintain them without accidentally undermining their safety guarantees.

 

4.1. Designing a Thread­safe Class

While it is possible to write a threadsafe program that stores all its state in public static fields, it is a lot harder to verify its thread safety or to modify it so that it remains threadsafe than one that uses encapsulation appropriately. Encapsulation makes it possible to determine that a class is threadsafe without having to examine the entire program.

 

The design process for a threadsafe class should include these three basic elements:

  • Identify the variables that form the object's state;

  • Identify the invariants that constrain the state variables;

  • Establish a policy for managing concurrent access to the object's state.

An object's state starts with its fields. If they are all of primitive type, the fields comprise the entire state. Counter in Listing 4.1 has only one field, so the value field comprises its entire state. The state of an object with n primitive fields is just the ntuple of its field values; the state of a 2D Point is its (x, y) value. If the object has fields that are references to other objects, its state will encompass fields from the referenced objects as well. For example, the state of a LinkedList includes the state of all the link node objects belonging to the list.

 

The synchronization policy defines how an object coordinates access to its state without violating its invariants or postconditions. It specifies what combination of immutability, thread confinement, and locking is used to maintain thread safety, and which variables are guarded by which locks. To ensure that the class can be analyzed and maintained, document the synchronization policy.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值