Code Locking
📋 Table of Contents
🎯 Lock Basics
// Script syntax
lock name="mylock" timeout=10 {
// Synchronized code here
criticalOperation()
}
// Template syntax
<bx:lock name="mylock" timeout="10">
<!-- Synchronized code here -->
</bx:lock>
// CFML compatibility
<cflock name="mylock" timeout="10">
<!-- Synchronized code here -->
</cflock>When to Use Locks
Lock Flow Diagram
🔐 Lock Types
1. Exclusive Locks (Write Locks)
2. Readonly Locks (Read Locks)
Lock Type Comparison
Feature
Exclusive
Readonly
Lock Type Interactions
📛 Named Locking
Basic Named Lock
Naming Conventions
Lock Name Characteristics
Named Lock Examples
Example 1: Cache Population
Example 2: Counter Increment
Example 3: Multiple Locks with Different Names
🎯 Scope Locking
Scope Lock Syntax
How Scope Locks Work
Available Scopes
Scope
Lock Granularity
Use Case
Scope Lock Examples
Example 1: Application Counter
Example 2: Session Data Update
Example 3: Server-Wide Configuration
Scope Lock vs Named Lock
⚙️ Lock Attributes
Attribute
Type
Required
Default
Description
Attribute Details
name - Lock Name
name - Lock Namescope - Scope Name
scope - Scope Nametimeout - Wait Time
timeout - Wait Timetype - Lock Type
type - Lock TypethrowOnTimeout - Timeout Behavior
throwOnTimeout - Timeout BehaviorAttribute Examples
🔄 Double-Check Locking Pattern
The Problem: Race Condition
The Solution: Double-Check Pattern
Double-Check Pattern Diagram
Real-World Examples
Example 1: Cache Population
Example 2: Singleton Initialization
Example 3: Application Initialization
Why Double-Check Works
⚠️ Deadlock Prevention
Deadlock Example
Deadlock Diagram
Deadlock Prevention Strategies
1. Consistent Lock Ordering
2. Use Minimal Timeout
3. Avoid Nested Locks
4. Use Lock Hierarchies
Deadlock Recovery
Deadlock Best Practices
☕ Advanced: Java Interop Locking
Using Java ReentrantLock
Using Java ReentrantReadWriteLock
Using Java Synchronized Blocks
Using Java Semaphores
Using Java CountDownLatch
Using Java CyclicBarrier
Using Java Atomic Variables
Using Java ConcurrentHashMap
Advanced Pattern: Custom Lock Manager
Comparison: BoxLang vs Java Locking
Java Interop Examples
Example 1: Rate Limiting with Semaphore
Example 2: Atomic Counter
Example 3: Thread-Safe Cache
💡 Best Practices
1. Use Minimum Timeouts
2. Prefer Named Locks Over Scope Locks
3. Always Use Double-Check Pattern
4. Use Descriptive Lock Names
5. Handle Timeouts Appropriately
6. Use Readonly Locks for Read Operations
7. Keep Lock Scope Minimal
8. Document Lock Dependencies
9. Monitor Lock Performance
10. Use Java Locks for Advanced Scenarios
📋 Summary
🔗 Related Documentation
Last updated
Was this helpful?
