Keep It Away From Me
Scope it way down…
A guideline to live by…
- Manage concurrent-based stuff managed in one place
- Close to where that stuff lives
Dependent State
Consider the following (incomplete) iterator:
Dependent State+Multi-Threaded
Use this code in a test:
What about this use:
And then in some test somewhere:
There’s a problem. How can we fix it?
- Client-based locking
-
Server-based locking
Client Based Locking
The client (user) of the common data locks:
Server-Based Locking
The server guards the dependent calls:
Here’s an updated client that now works:
Evaluate, between client-based and server-based locking
- Which do you prefer?
-
Which solution most reduces the scope of the shared data?
Client or Server-based?
When you have control of the code: Prefer server-based locking
- It reduces the possibility of error
- It reduces repeated code
- It will change your API (your client has change anyway)
- It enforces a single policy
- It reduces the scope of a multi-thread mutable variable
- It makes tracking down errors far easier
What if you don’t have control?
- Adapter to change the API & add Locking
- The Java collections use the collection object itself. Even so:
- Adapt
- OR better yet, use the thread-safe collections with extended interfaces
- Pick client-based locking only if it is impossible to use an adapter – which should be nearly never
Comments