How to create a multiple Threads
Thread classRunnable interfaceCallable interfaceExecutorService thread poolCompletableFuture APIVolatile Keyword :
Problems with volatile
- No atomicity for operations
count++involves read → modify → write, so multiple CPUs can overwrite each other's updates even though the variable isvolatile. - Cache coherence overhead
Everyvolatilewrite invalidates cached copies in other CPU cores, increasing cache traffic and reducing performance. - Memory fence overhead
volatileinserts CPU memory barriers (fences), preventing instruction reordering and slowing execution. - No mutual exclusion
Multiple CPU cores can still execute the same code simultaneously;volatileonly guarantees visibility, not exclusive access. - Not suitable for compound operations
Operations like increment, check-then-act, or read-modify-write require synchronization or atomic classes becausevolatilecannot prevent race conditions.
How can deadlock happen
Class Lock
Class object monitorObject Lock
Fail Fast vs Fail Safe Iterator