java classic interview questions

1) Can a volatile array be created in Java?
Yes, volatile arrays can be created in Java, but just a reference to the array, not the entire array. What I mean is that if you change the array pointed to by the reference, it will be protected by volatile, but if multiple threads change the elements of the array at the same time, the volatile identifier will not have the previous protection.

2) Can volatile make a non-atomic operation atomic?
A typical example is having a member variable of type long in a class. If you know that the member variable will be accessed by multiple threads, such as counter, price, etc., you'd better set it to volatile. Why? Because reading a variable of type long in Java is not atomic and needs to be split into two steps, if one thread is modifying the value of the long variable, the other thread may only see half of the value (the first 32 bits). But reads and writes to a volatile long or double variable are atomic. \

3) What is the practice of volatile modifier?
One practice is to decorate long and double variables with volatile so that they can be read and written atomically. Both double and long are 64 bits wide, so the read of these two types is divided into two parts, the first 32 bits are read first, and then the remaining 32 bits are read. This process is not atomic, However, reads and writes of volatile long or double variables in Java are atomic. Another role of the volatile fixer is to provide a memory barrier, such as is used in distributed frameworks. Simply put, the Java memory model inserts a write barrier before you write a volatile variable, and inserts a read barrier before reading a volatile variable. This means that when you write a volatile field, you can guarantee that any thread can see the value you write, and at the same time, before writing, you can also guarantee that any value update is visible to all threads, because the memory barrier will All other written values ​​are updated to the cache.

4) What guarantees do volatile type variables provide?
Volatile variables provide ordering and visibility guarantees, e.g. JVM or JIT reorder statements for better performance, but volatile variables will not be reordered with other statements even if assigned without a synchronized block. Volatile provides happens-before guarantees, ensuring that changes made by one thread are visible to other threads. In some cases, volatile can also provide atomicity, such as reading 64-bit data types, such as long and double are not atomic, but volatile types of double and long are atomic.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325646699&siteId=291194637