IV. Multi-Threading Basics
- Multithreaded code allows concurrency of execution w/o heavy weight
- Multiple threads are swapped on and off cpu, or run concurrently on multiple-cpu boxes.
- An app's threads share same process resources
- file handles,
- heap memory space,
- the resources of the JVM.
- Each thread has a program counter and stack memory for local data (non-static).
- Synchronization of access to resources and code is necessary.
- Synchronization can be thought of as single-file access
one at a
- Another synchronization concept: thread shutdown.
- Controlling thread joins with thread it's stopped - insures proper completion.
B. Classic Concurrency Problem
- The statement k++ is not thread-safe (depending on k). Consider the
- fetch k from memory to register
- increment k in register
- store k from register to memory.
- Now, consider two threads, each accessing k - there is a timing issue.
- The result of above will be as if only one iteration occurred.
- Solution: make sure T1 is not interrupted between time 1 and time 5.