1/11
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
Thread vs process
Thread: small processing unit
Process: running program, may contain multiple threads, that share the env;
Java threads
Platform threads - it’s mapped 1-1 to OS threads
Carrier threads - platform threads, that carry virtual threads
Virtual threads - lightweight threads - logical threads, not platform
→ meaning: carrier threads do the work, they switch between virtual threads(tasks), so when a virtual thread is blocked, the carrier thread can carry on to do something else in the meantime.
What is concurrency?
Multiple threads/processes run at the same time;
creating threads
Use the Runnable functional interface with the void run method, to define the task.
Create thread:
var builder = Thread.ofPlatform(); Thread t = builder.start(runnable);
var builder = Thread.ofVirtual(); Thread t = builder.start(runnable);
Thread t = new Thread(runnable); t.start();
asynchronous vs sync code
Asynchronous calls are non blocking, the main thread continues to run without waiting for result;
thread.join()
Make main thread wait until the other thread finishes.
daemon thread
Runs in the background, it has low priority. It does not prvent the JVM from exiting. Virtual threads are daemon threads;
Thread life cycle, + how to get state
New
Runnable: running or ready to run
blocked
waiting
timed_waiting
terminated
get state: t.getState();
ConcurrencyAPI usage and components
Useful for managing threads;
usage: use it within try with resources!!!!
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(runnable); service.submit(runnable/callable)
callable - same as runnable but has generic return type!
execute - returns nothing
submit - returns Future<T> result;
result.get(); // this blocks the caller
useful:
newSingleThreadScheduledExecutor() - schedule task in the future
newCachedThreadPool()
newFixedThreadPool()
Thread safe
Safe even when multiple concurrent threads execute/use it;
synchronization/thread safety tools
Atomic classes: AtomicInteger, AtomicLong - used for atomic operations
synchronized blocks/methods: executed by one thread at a time
lock - ReentrantLock - lock, unlock, trylock
barrier - CyclickBarrier
concurrent collections - ConcurrentHashMap…
Threading/Concurrency problems
dead lock
live lock
starvation