Java Concurrency Concepts
- Thread actions are implemented by using method
- Thread is scheduled to run using
startmethod of a
- Thread scheduler will allocate portions of CPU time (time-slice) to excute thread actions.
- The return of method
runterminates the thread.
- Concurreny doesn't mean actual phsical parallel execution.
- In which order threads will actually perform the actions is really not predictable, this is a stochastic process.
- You can't put 2 different pieces of logic from different threads to take the same time-slice on the same CPU core.
- There is some degree of parallelism but it depends.
Thread Life Cycle
- You can go from whatever state to runnable state (except
terminated) and from runnable state to whatever other state except
- Almost every state needs to transit throught the
- Transitions to the running state are not immediate -- thread scheduler needs to allocate next available CPU time slot for this thread.
boolean b = thread1.isAlive();
Thread.State phase = thread1.getState();
Because of the parallelism which is behind the scenes, the state could have changed, in other words, it's not exactly up-to-date.
- A thread in a
runnablestate may check if it has received an interrupt signal.
- A thread that has entered a
timed waitingstate must catch
InterruptedException, which puts it back to
runnablestate, and then decide what it should do.
- How would the thread react to an interrupt signal is up to the programmer.
Monitor object helps to coordinate order of executions of threads.
- Any object can be used as a monitor.
- It allows threads to enter blocked or waiting states.
- It enables mutual exclusion of threads and signaling mechanisms.
synchronizedenforces exclusive access to the block of code. A thread would be blocked waiting for the previous thread to complete execution of a synchronized block before it can proceed.
synchronizedis used to block against static context, then all the different instances of the same class will be blocking each other against the class itself, as class context is shared among all instances.