Concurrent programming common knowledge points
- Have you ever used multi-threading in your daily business? Can you give some examples of multi-threading business scenarios?
Asynchronous tasks: user registration and log recording Scheduled tasks: periodically backing up logs and databases Distributed computing: Hadoop processing tasks MapReduce and master-wark server programming: Socket network programming, one thread for each connectionCopy the code
- Can you name some data structures that are not thread-safe?
HashMap ArrayList LinkList
Copy the code
- What methods can be used to ensure thread-safety in Java?
Locking, such as Synchronize and ReentranLock, uses volatile to declare variables, lightweight synchronization, and does not guarantee atomicity. (Explanation required) Use thread-safe classes (AtomicXXX, concurrent container, Synchronization containers CopyOnWriteArrayList, ConcurrentHashMap, ThreadLocal local private variables, semaphore, etcCopy the code
- Know the volatile keyword? Can you explain how it’s different from Sychronzed
Volatile is a lightweight sychronized, volatile variable that ensures the visibility of shared variables. If a variable is volatile, it is immediately visible to other threads, preventing dirty reads. Ensure visibility, but not atomicity synchronize: Ensure visibility, also ensure atomicityCopy the code
- Usage scenarios
Write to a variable that depends on the current value, such as num++, num=num+1, is not an atomic operation. 2. Since instruction reordering is disabled, jVM-specific optimizations are eliminated, resulting in lower efficiency.Copy the code
- Why do dirty reads occur?
The JAVA Memory Model (JMM) specifies that all variables are stored in main memory, that each thread has its own working memory, and that the thread does all its work on variables in the working memory. Can't directly to main memory Using volatile modify variables Each read money must be from the main memory access the latest attribute values Every time write need voliate keyword in main memory at once modified variable to see their latest values at any time, if thread 1 variable to modify the variable v, then the thread 2 is can see right awayCopy the code