Synchronisation Flashcards
What is conditional synchronisation?
Threads only execute or continue to run if condition has been met, usually when it has been notified by another thread.
What is mutual exclusion?
A thread is able to gain a mutex (mutually exclusive lock) to ensure it will keep synchronised access to the method or block.
Similar to an atomic action
What is the lost deposit problem?
Due to no synchronisation, money can be deposited (or withdrawn) twice, and the final balance will get overwritten by one of the threads without taking account of the other’s actions.
What are locks?
Only one thread can get a lock on a synchronised method or block at a time.
If two thread attempt to get a lock, one will succeed and the other will fail, resulting in having to wait
Java creates locks for each object
With a synchronised method, a thread must obtain a lock before executing the method statements
What are synchronised methods?
Used with classes to ensure atomic actions and that only one thread can access at any one time
What are synchronised blocks?
Block of code within a method can also be synchronised.
What is the issue with synchronised blocks?
Difficult to maintain a record of across code
What is the ‘wait’ used for in Conditional Synchronisation?
To enable waiting until a notify has been sent from another thread
What is the ‘notify’ used for in Conditional Synchronisation?
To inform the waiting thread that the wait is over and that they should be able to proceed with their function.
What is the ornamental garden example?
Two entrances, want to count total of who came in and from which entrance.
Needs to be synchronised addVisitor method to get the correct total number of visitors
What is deadlock?
Where no threads are ever able to get access to required resources.
Example: 2 threads, 2 objects with locks, can create deadlock as each object is always waiting on the other.
What is starvation?
When resources are allocated but some threads never get access.