Java Multithreading for Senior Engineering Interviews (Notes from an Educative course)
The simplest example to think of a concurrent system is a single-processor machine running your favourite IDE. Say you edit one of your code files and click save, that clicking of the button will initiate a workflow which will cause bytes to be written out to the underlying physical disk. However, IO is an expensive operation, and the CPU will be idle while bytes are being written out to the disk.
Whilst IO takes place, the idle CPU could work on something useful and here is where threads come in — the IO thread is switched out and the UI thread gets scheduled on the CPU so that if you click elsewhere on the screen, your IDE is still responsive and does not appear hung or frozen.
Threads can give the illusion of multitasking even though at any given point in time the CPU is executing only one thread. Each thread gets a slice of time on the CPU and then gets switched out either because it initiates a task which requires waiting and not utilising the CPU or it completes its time slot on the CPU. -> Context switch, time-slicing.
Of course, if we have multiple cores then a multiple thread program can execute concurrently. Each thread by a different cpu core.
Benefits of threads
- Higher throughput, though in some pathetic scenarios it is possible to have the overhead of context switching among threads steal away any throughput gains and result in worse performance than a single-threaded scenario. However such cases are unlikely and an exception, rather than the norm.
- Responsive applications that give the illusion of multi-tasking.
- Efficient utilisation of resources. Note that thread creation…