Analysis of Java interview questions

Time:2021-9-25

1. volatile

  1. Memory visibility: when variables in main memory are used in a multithreaded environment, they will be copied to the thread’s private memory,volatileKeyword modified variables can ensure the consistency of the same variable between main memory and thread private memory.
  2. Atomicity is not guaranteed:volatileKeyword modified variables can guarantee the atomicity of a single operation (instruction rearrangement is prohibited), but cannot guarantee the atomicity of multiple operations (such as + + or –).
  3. Prohibit instruction rearrangement: byte code instructions compiled by the JVM are not necessarily executed in the encoding order, but are usedvolatileKeyword modified variables prohibit bytecode instruction rearrangement when performing operations.

2. CAS(CompareAndSet)

CompareAndSetyesUnsafeClassnativeMethod, inrt.jarIn,nativeModified methods can directly operate on specific memory like pointers in C language.

CAS is a concurrent primitive of CPU (the execution of primitives must be continuous and the execution process cannot be interrupted)

public class AtomicInteger extends Number implements java.io.Serializable {
    private volatile int value;
    public final boolean compareAndSet(int expect, int update) {
            return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
        }

Compareandset is used to obtain the variable value in the current main memory as the thread’s private memoryvalueAnd expected valueexpectCompare and update if equalvalueValue isupdateAnd return true, otherwise it will not be updated and return false.

Disadvantages of compareandset:

  1. If the comparison results are not equal, it will keep trying, which may bring great overhead to the CPU.
  2. Only atomic operations of one shared variable can be guaranteed.

3. ABA

ABA problem means that among two or more threads with a large difference in execution frequency, the thread with high execution frequency modifies the value of main memory for many times without the knowledge of other threads, and finally modifies it to the original value, causing other threads to think that the value in main memory has not changed.

ABA problem will be found in programs that pay attention to the execution process. For programs that only pay attention to the call results, this problem can be ignored.

//ABA problem demonstration and solution

Solution: atomic reference

Atomic referenceAtomicReference<V>A Java class can be encapsulated as an atomic object. Using this feature to combine timestamp with atomic reference can solve the ABA problem. Encapsulated timestamp classes have been provided in JavaAtomicStampedReference<V>

4. Thread safety of collection class

Example of ArrayList concurrency exception

ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 30; i++) {
    new Thread(()-> {
        list.add(UUID.randomUUID().toString().substring(0, 8));
        System.out.println(list);
    }, "t" + i).start();
}

Exception Name: java.util.concurrentmodificationexception

Solution:

  1. useVector<E>Vector<E>The operation will be locked to ensure data consistency.
  2. Collections.synchronizedList(new ArrayList<>()), encapsulate thread unsafe collections as thread safe collections.
  3. useCopyOnWriteArrayList<E>Achieve read-write separation.

Copyonwritearray source code

public boolean add(E e) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] elements = getArray();
        int len = elements.length;
        Object[] newElements = Arrays.copyOf(elements, len + 1);
        newElements[len] = e;
        setArray(newElements);
        return true;
    } finally {
        lock.unlock();
    }
}

When you write to a set, you will lock it first, copy the current set, write to the copied set, and finally overwrite the written set with the original set, and then unlock it.

5. Pointer reference problem

class Person() {
    public int age;
    public String name;
    public void setAge(int age) {
        age = 30;
    }
    public void setName(Person person) {
        person.name = "xxx";
    }
    public void setName(String name) {
        name = "str";
    }
}

Demo case 1 = 3

//Case 1: the setage method changes the value of the formal parameter, which is a copy of the argument variable. Therefore, changing the value of the copy does not affect the value of the variable itself

6. Thread lock

6.1. Fair lock / unfair lock

//Reentrantlock defaults to a non fair lock

Fair lock means that multiple threads acquire locks according to the order in which they apply for locks, and abide by the first come, first served principle; Non fair locks may apply first and then obtain the lock. The advantage of unfair lock is that the throughput is relatively large.

Note:synchronizedIt belongs to unfair lock.

6.2. Reentrant lock (recursive lock)

When there are nested locks in the code, the same thread will automatically acquire the lock when entering the internal code after the external code acquires the lock.

synchronizedandReentrantLockAre typical reentrant locks

6.3. Spin lock

When the thread that obtains the lock fails, it will not block immediately, but will try to obtain the lock in a circular way

AtomicReference<Thread> reference = new AtomicReference<>();

6.4. Exclusive lock (write lock) / shared lock (read lock) / mutex lock

Reentrantlock and synchronized are exclusive locks

The principle of read-write lock lies in the separation of read and write, the atomicity of write operation should be guaranteed, and the operation process cannot be interrupted; Read operations can share locks with multiple threads.

ReentrantReadWriteLock lock = new ReentrantReadWriteLock()

6.4. Lock and condition

When judging conditions in multithreading, you should use while instead of if, because while can judge whether the conditions are met again after the thread is awakened, and if will execute directly

//Create a condition through reentrantlock
  1. OneReentrantLockYou can create multipleCondition
  2. When called on thread acondition.await()Function can make the current thread in a blocking state; When thread B callscondition.signal()Function can wake up thread a.
  3. OneConditionCan be bound in multiple threads, usingcondition.signalAll()Can wake up all blocked threads if calledcondition.signal()One of them will wake up randomly.

7. CountDownLatch/CyclicBarrier/Semaphore

7.1. Countdown latch

Countdown lock. When countdownlatch is initialized, the countdown time will be specified,countDown()Each time the function is executed, the value of the counter will be decremented by one. When the countdown is 0await()The blocking state will end, otherwise it will wait all the timecountDown()The function executes until the timing reaches 0.

int count = 5;

7.2. Cyclicbarrier

The initialization parameters of the collector contain two items: the first is the number of collections that meet the conditions, and the second is the threads that execute after the conditions are met.

When invoked in threadsawait()Function, the number of collections will be increased by one, and then the collector will judge whether the current number of collections meets the conditions. When the number is met, the threads in the initialization parameters will be executed.

int count = 5;

7.3. Semaphore

When multiple threads preempt multiple resources, when the resources are insufficient to allocate to all threads, in order to ensure that all threads can allocate resources, a controller similar to a semaphore can be used to limit the flow.SemaphoreThe constructor of needs to pass in a limited number of resources. This class will maintain this number of resources when the thread callsacquire()Reduce the number of resources by one when using the function; When a thread callsrelease()Add one to the number of resources when using the function; When a thread requests a resource, it will be blocked if the number of resources is 0.

Semaphore semaphore = new Semaphore(3);

8. Blocking queue

  1. Arrayblockingqueue: a finite blocking queue composed of arrays
  2. Linkedblockingqueue: a limited blocking queue composed of linked lists (the default size is integer. Max_value)
  3. Priorityblockingqueue: an unbounded blocking queue that supports priority
  4. Delayqueue: delay unbounded blocking queue supporting priority
  5. Synchronousqueue: a blocking queue that does not store elements, a queue for a single element
  6. Linkedtransferqueue: an unbounded blocking queue composed of linked lists
  7. Linkedblockingdeque: a bidirectional blocking queue composed of linked lists

    Exception group function

    BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);

    Return bool value group

    BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);

    Blocking group

    BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);

    SynchronousQueue

    BlockingQueue<String> queue = new SynchronousQueue<>();

9. Thread pool

9.1. Thread pool 7 parameters

  1. Corepoolsize: number of resident core threads in the thread pool
  2. Maximumpoolsize: the maximum number of threads that the thread pool can hold at the same time
  3. Keepalivetime: survival time of redundant idle threads
  4. unit: keepAliveTimeTime unit
  5. Workqueue: task queue. When all core threads are busy, the newly added thread will be put into the task queue; When the task queue overflows, the thread pool will open new threads until the number of threads reaches the maximum (when the task queue overflows, the newly added threads will preempt the threads in the task queue for execution)
  6. Threadfactory: factory that generates threads
  7. Handler: reject policy when thread pool overflows

9.2. Rejection strategy

  1. Abortpolicy (default): throw rejectedexecutionexception directly
  2. Callerrunspolicy: returns the task to the caller without throwing an exception or discarding the task
  3. Discard oldest policy: discards the longest waiting task in the queue, then adds the current task to the task queue and tries to submit the task again
  4. Discardpolicy: directly discard the task without throwing an exception

9.3. Common methods

  • execute(Runnable thread): perform tasks
  • submit(Callable<T> callable): submit task, returnFuture<T>
  • suutdown(): stop the thread pool after waiting for unfinished tasks to execute
  • shutdownNow(): stop the thread pool immediately (use the interrupt method to terminate unfinished tasks)
  • awaitTermination(timeout, unit)Blocking: stop the thread pool after all tasks are executed
  • invokeAll(Collection<? extends Callable<T>> tasks): submit tasks in batch and wait for all tasks to be executed to return the result listList<Future<T>>
  • invokeAny(Collection<? extends Callable<T>> tasks): batch submit tasks and return the results of the first completed task

    9.4. Creation of thread pool

    Commands in Alibaba java development manual are prohibitedExecutorsCreate a thread pool using the returned thread pool object:

    Analysis of Java interview questions

    //Create thread pool manually

    How to determine a reasonable number of thread pools?

  1. CPU intensive business (large amount of computation and less IO operations): CPU cores + 1
  2. IO intensive (blocking coefficient: 0.8 ~ 0.9)
    1. CPU cores / (1 – blocking factor)
    2. Number of CPU cores * 2

      10. Deadlock problem

      Java deadlock demo

      Deadlock problem solution

calong > jps -l
10540
11436 jdk.jcmd/sun.tools.jps.Jps
12508 club.calong.jvm.demo.DeadLock
5788 org.jetbrains.jps.cmdline.Launcher
calong > jstack 12508
Java stack information for the threads listed above:
===================================================
"t3":
        at club.calong.jvm.demo.SyncThread.run(DeadLock.java:22)
        - waiting to lock <0x000000076b577cf8> (a java.lang.Object)
        - locked <0x000000076b577d18> (a java.lang.Object)
        at java.lang.Thread.run(Thread.java:748)
"t1":
        at club.calong.jvm.demo.SyncThread.run(DeadLock.java:22)
        - waiting to lock <0x000000076b577d08> (a java.lang.Object)
        - locked <0x000000076b577cf8> (a java.lang.Object)
        at java.lang.Thread.run(Thread.java:748)
"t2":
        at club.calong.jvm.demo.SyncThread.run(DeadLock.java:22)
        - waiting to lock <0x000000076b577d18> (a java.lang.Object)
        - locked <0x000000076b577d08> (a java.lang.Object)
        at java.lang.Thread.run(Thread.java:748)
Found 1 deadlock.

11. JVM parameters

  1. java -XX:+PrintFlagsInitial -version: view the default initial values of JVM parameters
  2. java -XX:+PrintFlagsFinal -version: view the modified JVM parameters and the modified values
  3. Java - XX: + printflagsfinal - XX: parameter = value t: modify JVM parameters
  4. jinfo -flags PID: View JVM parameters for Java processes
  5. Jinfo - flag parameter PID: view the specified JVM parameters for the java process
  6. java -XX:+PrintCommandLineFlags: viewing the Java runtime command line specifying JVM parameters

Common parameters:

  1. -XSS (- XX: threadsacksize): the stack size of a single thread. The default is 512 ~ 1024k
  2. -XMS (- XX: initialheapsize): the initial memory size, which is 1 / 64 of the physical memory by default
  3. -Xmx (- XX: maxheapsize): the maximum allocated memory, which is 1 / 4 of the physical memory by default
  4. -20: Metaspacesize: the size of the meta space, which is not in the virtual memory. The size is only limited by the local memory. The default size is 20.8m
  5. -20: Printgcdetails: view the CG running log and memory usage of Java threads
  6. -20: Survivorratio: set the space ratio of S0 / S1 in the new generation Eden
  7. -20: Newratio: set the proportion of heap memory structure of the new generation and the old generation
  8. -20: Maxtenuringthreshold: sets the maximum age of garbage

12. Citation issues

  1. Strong reference:Object obj = new Object();, strong references are never recycled under any circumstances.
  2. Soft reference:SoftReference<Object> obj = new SoftReference<>(new Object()), when the system memory is sufficient, it will not be recycled, and when it is insufficient, it will be recycled.
  3. Weak reference:WeakReference<Object> obj = new WeakReference<>(new Object()), the object will be recycled as long as the GC is run. stayWeakHashMap<T>If willKeypointnullAfter running GC, thenKeyandValueWill be recycled.
  4. Virtual reference:PhantomReference<Object> obj = new PhantomRefence<>(new Object()), a virtual reference object. The object must match the reference queueReferenceQueue<T>use.

    Weak reference and virtual reference objects will be put into the reference queue before being recycled by GC. The method of reference queue is usedpoll()You can get the object being placed.

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

A detailed explanation of the differences between Perl and strawberry Perl and ActivePerl

Perl is the abbreviation of practical extraction and report language “practical report extraction language”. Application of activestateperl and strawberry PERL on Windows platformcompiler。 Perl   The relationship between the latter two is that C language and Linux system have their own GCC. The biggest difference between activestate Perl and strawberry Perl is that strawberry Perl […]