Java Multi-Threading Flashcards
Data Race
Two or more threads in a single process access the same memory location concurrently and, at least one of the accesses is for writing, and the threads are not using any exclusive locks to control their accesses to that memory
Deadlock
Two threads hold locks on different resources, each waiting indefinitely for the other to release its lock
Synchronized method
A method that can only be executed by a single thread at a time
Method ‘lock’
enclosed in a try/finally because if the ‘try’ code throws an exception, the lock must be unlocked or it will block other threads forever. Only one thread can lock/unlock at a time (for each lock)
Semaphore
Controls access to shared resources through the use of a counter. If counter > 0, access is allowed, otherwise denied. If counter is < 0, thread will be blocked until a different thread releases their permit.
Thread vs Process
Thread: smallest units of the particular process. Has the ability to execute different parts of the program at the same time.
Process: refers to a program that is in execution
User Thread vs Daemon Thread
User thread: JVM waits for user threads to finish their tasks before termination. Created by user to execute tasks concurrently. High-priority, required to run in foreground
Daemon thread: JVM does not wait for daemon threads to finish their tasks before termination. Created by JVM. Low-priority used for garbage collection, releasing memory of unused objects, etc.
Wait() vs Sleep() methods
Wait - causes current thread to wait and sleep. Releases the lock for inter-thread communication.
Sleep - pauses or stops the execution of the current thread. Does not release lock.
Start() vs Run()
Start - starts the execution of a newly created thread. this newly created thread executes the task that is kept in the run method
Run - starts the execution of the same thread. No new thread is created
Join()
pauses the execution of a thread until thread 1 in thread.join(thread1) is dead or completed.
Garbage Collection
automatic memory management. Three phases - mark, delete, compact/copy. A garbage collector finds objects that are no longer required by the program and deletes them to free up memory space
Volatile variable
Allows a field to become visible to all readers (threads) after a write operation completes on it. Without volatile, some threads could see some non-updated value.
Synchronized Block
Locks part of the program between parentheses after the synchronized keyword. Preferred to synchronized method because it doesn’t lock up the whole method.
Livelock
state of threads changes between one another without making any progress. Threads are not blocked but their execution is stopped due to the unavailability of resources
BlockingQueue
blocks a thread from trying to insert into a full queue until another thread takes from it, and vice versa