path | title |
---|---|
/learnings/java_concurrency |
Learnings: Java: Concurrency |
See also:
- Learning_Java_Hotspot_Memory_Zones_And_Threads
Q: how much are any one particular thread or executioner group actually using the CPU, vs waiting for sync IO/network? Profile this: this will tell you how much you can cheat WRT CPU core count...
can be a method declaration
public void syncronized addIt(int i) { MyClass.a += i;}
Can also do it as a block in a method
public addIt(int i) {
logger.info("into");
syncronized(Myclass.class) {
Myclass.a += i;
}
}
OS may cache value of a variable shared across threads. volatile will make sure to read this from memory instead
- [Source]: high performance apps with Java 9
*Atomic... classes for adding stuff
- ComcurrentHahMap, ArrayList, etc —- more efficient than wrapping self
Manually creating / waiting on a lock ReentrantLock can pass "fair" flag, which will make sure to give priority access to longest waiting requestor.
Fixed thread pool: if threads are taken up wait in line for the next availible
cached thread pool: fixed thread pool that will reuse previously constructed threads threads that have not been used in 60 seconds thread will be removed
single thread executor - single worker thread off an unbounded queue. Tarmination means replacement thread is created.
java.concurrent.Future from Java 5
Guava brought ListenableFuture
whene you could do addCallback
, onFailure
.
JDK 8's CompletableFuture implements Future's interface, but using Java 8's streams and lambdas stuff.
(these are backed by CompletionStage
. CompletableFuture
can be used as a CompletionStage
).
When you run a CompletableFuture, if you don't provide a thread pool / executor one will be provided for you.
.thenApply
<-- really map
.thenApplyAsync
<-- then apply but can jump to another thread pool. Maybe you have different thread pool for different purposes (ie for different thread pool characteristics, etc). Can also provide your own executor, else one will be assigned for you.
.thenCompose
<-- chains future together
just use the fact that these are closures and grab something from the outside scope.