Concurrency Lecture 3 Flashcards
How do we prevent race conditions and interleaving threads?
By using synchronization.
What are three ways to synchronized your class being accessed by the threads?
- Synchronized Methods
- Synchronized Blocks
- Lock Objects
What is method synchronization?
When each method that allows access to the shared data has the prefix ‘synchronized’ before the method name.
public synchronized void MyFunction() {
…
}
What effects does synchronization (method, blocks and locks) have?
All threads that invoke synchronized methods for the same object, will wait until the thread in that critical code is done.
When the critical code is run the state of the object is invisible to all threads but the one accessing it.
When a critical code is exited the state of the object is visible to all threads.
What is block synchronization?
When a synchronized keyword with the object as a parameter is added around the code that accesses its shared data. This synchronizes the object for the region of code it surrounds.
…
synchronized (Object) {
// change data in here.
}
…
What is a lock object?
A lock is created along with other parameters in the declaration of the shared class.
This lock can then be used to lock the object to use only be the thread who called the lock method. Lock right before critical code, and then unlock after when finished.
Instance:
Lock fundsLock;
Create in constructor: fundsLock = new ReentrantLock()
Code: ... fundsLock.lock(); try { ... // Change the data ... } finally { fundsLock.unlock(); } ...