Java Pro Flashcards
Thread, process
Thread - smallest unit of execution that can be scheduled by the OS on CPU core
Process - grouping of associated threads executing in shared environment - memory space and can communicate directly with one another
System thread vs user-defined thread in JVM
system thread
- created by JVM
- runs in BG
- GC thread
user-defined thread
- created by app dev to accomplish a specific task
All jvm apps are multi-thread but may be single-user-defined-threaded (the main one calling… main())
Daemon thread
Thread that will not prevent JVM from exiting after program fiinishes
Java app terminates when the only threads running are daemon
GC thread is daemon thread
User-defined threads can also be marked as daemon
Thread scheduler
Determines which thread should be executing
Might be round-robin schedule - all threads receive equal number of CPU cycles, threads revisited in circular order
When thread allotted time is complete but it didn’t finish yet - context switch
threads can have priorities - higher priority thread will interrupt the lower-priority one if its executing
Context switch
Process of storing thread’s current state and later restoing the state of the one to continue exec which cost a bit CPU time
Runnable
functional interface, takes no args, returns nothing
Commonly used to define the work for separate thread
when java Thread is run?
After start method is called it can be scheduled by OS for execution but exact time is unknown
To extend thread or implement Runnable
- if multiple tasks would share rules like priority extended thread could be useful
- Extending thread locks you to base concrete class
- Implementing runnable allows for better separation-of-concerns from object performing the task
- Runnable can be used in Concurrency APIs
ExecutorService bitch - fuck explicit threads
While while loop polling is bad practice
Spinning while loop without delay like sleep eats a lot of CPU resources for no reason
Thread executor
They create non daemon threads when first task is submitted so shutdown should be called
Shutdown prevents new tasks from being submitted
Previously submitted tasks will continue
New thread executor
Active -> Shutting down -> Shutdown
shutdownNow() would attempt to stop running tasks, discards ones not started yet; returns list of not started tasks
Threads that never terminate cannot be interrupted though
Do not implements AutoClosable - must use finally
Task submission
- execute - async fire-and-forget, no way to get result
- submit - returns Future to determine state of task
Callable
Checked Exception
call method
Can return value
Runnable equivalent for concurrency APIs
Thread Pools
Group of pre-instantiated, reusable threads available to perform a set of arbitrary tasks
- newSingleThreadExecutor - single worker thread operating off an unbounded queue, results processed sequentially in order of submission
- newSingleThreadScheduledExecutor - can schedule commands to run after delay or periodically
- newCachedThreadPool - creates new threads as needed, will reuse previously constructed ones when they’re available; unbounded thread pool size; good for many short-live async tasks; long lived processes - nope
- newFixedThreadPool - reuses fixed num of threads, operates off a shared unbounded queue
- newScheduledThreadPool - pool that can schedule
IO tasks that depend on external resources (file system, network, db) are good for large thread pool as tasks are not CPU bound and there’s a lot of waiting
java.util.concurrent.atomic
Package hlping coordinate access to primitive values and object references
AtomicBoolean, AtomicInteger, AtomicIntegerArray, AtomicLong, AtomicLongArray, AtomicReference, AtomicReferenceArray
get, set, getAndSet, incrementAndGet…
Sycnhronized block
monitor = lock - mutual exclusion - at most one thread executes marked segment of code at given time
synchronized keyword
Any object can be monitor but must be the same instance to work
Static synchronization
Can be done using class object (Class.class) Works for all instances
Concurrent collections
Convenient classes, prevent mistakes in custom implementations like forgetting synchronizing some method
Solve Memory consistency errors - two threads have inconsistent views of the same data (writes on one thread not seen by other)
When 2 threads modify non-concurrent collection JVM may throw ConcurrentModificationException at runtime (can happen also when modifying collection while iterating it)
blockingdequeue/queue - offer, offerFirst, offerLast - with timeouts and throws interrupted exc
Collections.synchronizedXyz to get concurrent safe reference for existing non-concurrent collection
Sync is on get/set but not for iterators so needs to use synchronized block