PATH |
- Inherits from:
- Object
- Implements:
- NSLocking
- Package:
- com.webobjects.foundation
An NSLock object is used to coordinate the operation of multiple threads of execution within the same application. An NSLock object can be used to mediate access to an application's global data or to protect a critical section of code, allowing it to run atomically.
An NSLock object represents a lock that can be acquired by only a single thread at a time. While one thread holds the lock, any other thread is prevented from doing so until the owner relinquishes the lock. An application can have multiple NSLock objects, each protecting different sections of code. It's safest to create all of the locks before the application becomes multi-threaded, to avoid race conditions. If you want to create additional locks after the application becomes multi-threaded, you should create the new lock inside a critical code section that is itself protected by an existing lock.
The basic interface to NSLock is declared by the NSLocking interface, which defines the lock and unlock methods. To this base, NSLock adds the tryLock methods. Whereas the lock method declared in the interface doesn't return until it is successful, the methods declared in this class add more flexible means of acquiring a lock.
An NSLock could be used to coordinate the updating of a visual display shared by a number of threads involved in a single calculation:
boolean moreToDo = true; NSLock myLock = new NSLock(); ... while (moreToDo) { /* Do another increment of calculation */ /* until there's no more to do. */ if (myLock.tryLock()) { /* Update display used by all threads. */ myLock.unlock(); } }
The NSLock, NSMultiReaderLock, and NSRecursiveLock classes all adopt the NSLocking protocol and offer various additional features and performance characteristics. See the NSMultiReaderLock and NSRecursiveLock class descriptions for more information.
- Constructors
- NSLock
- Instance methods
- lock
- lockBeforeDate
- toString
- tryLock
- unlock
public NSLock()
public synchronized void lock()
public boolean lockBeforeDate(NSTimestamp timestamp)
tryLock(NSTimestamp timestamp)
instead.
public String toString()
public synchronized boolean tryLock()
true
if successful and false
otherwise.
public synchronized boolean tryLock(long msec)
true
if the lock is acquired within this time limit. Returns false
if the time limit expires before a lock can be acquired.
public boolean tryLock(NSTimestamp timestamp)
true
if the lock is acquired within this time limit. Returns false
if the time limit expires before a lock can be acquired.
public synchronized void unlock()
© 2001 Apple Computer, Inc. (Last Published April 17, 2001)