Java 2022 (Java Basics) latest interview questions and answers

java basics

Java 8 basic data types

type Data type and occupied bytes
Integer byte (1 byte) short (2 bytes) int (4 bytes) long (8 bytes)
floating point float (4 bytes) double (8 bytes)
character type char (3 bytes)
Boolean boolean (1 byte)

The difference between ArrayList and LinkedList

  • ArrayList is implemented using arrays, and LinkedList is implemented based on linked lists.
  • The biggest difference between arrays and linked lists is that arrays can be accessed randomly , while linked lists can only be traversed from the beginning.
  • The efficiency of checking ArrayList is high
  • ArrayList is efficient when the addition and deletion are at the end and the amount of data is large, and LinkedList is efficient in other places.

Due to the continuity of the array on the physical memory, when adding or deleting elements, the subsequent elements will be moved by one bit, so the efficiency is relatively low, while the linked list can easily disconnect from the next element and insert new elements directly. Or it is more efficient to remove old elements, but when additions and deletions are at the end, there is no need to move subsequent elements, so ArrayList is faster.

Difference between singly linked list and doubly linked list

Singly linked list
composition : the link direction is unidirectional, and the traversal of the linked list should be read sequentially from the head; the node is composed, the head pointer points to the first node that becomes the head node, and ends at the last pointer pointing to NULL.
Advantages : It is simple to add and delete nodes in the one-way linked list, and there will be no infinite loop when traversing.
Disadvantage : Can only traverse from beginning to end. You can only find the successor, not the predecessor, that is, you can only move forward.

Doubly linked list
composition : The doubly linked list contains two pointers, pre points to the previous node, next points to the next node, but the pre of the first node head points to null, and the tail of the last node points to null.
Advantages : can advance and retreat, can find predecessors and successors.
Disadvantages : It takes up a lot of memory, needs to allocate an additional precursor pointer, and traverses complicatedly.

Two-way circular linked list
composition : The difference between a two-way circular linked list and a two-way linked list is that the pre of the first node points to the last node, and the next of the last node points to the first node, which also forms a cycle. LinkedList is composed of a two-way circular list.
Advantages : Starting from any node in the circular linked list, any other node can be found.

HashMap

underlying implementation

JDK 1.7
storage structure : array + linked list
Insertion method : head insertion method
Expansion method : expand first, then add
disturbance function : 4 bit operations + 5 XOR operations are required

JDK 1.8
storage structure : array + linked list + red-black tree
Insertion method : tail insertion method
Expansion method : add first, then expand
Disturbance function : perform 1 bit operation + 1 XOR operation

Reasons for introducing red-black tree

In order to solve the problem of query efficiency caused by too long linked list after hash collision.

Red-black tree transformation conditions

The length of the array is greater than 64 , and the length of the linked list is greater than 8 before it is converted from a linked list to a red-black tree.

When the length of the array is less than 64, the array + linked list takes up less space than the red-black tree, and the self-balancing of the red-black tree is more time-consuming. When the hash collision is serious, it is better to expand the capacity first to resolve the conflict.

thread safety issues
  • JDK1.7 : Because of the head insertion method , the situation of the ring list when the expansion operation is performed concurrently.
  • JDK1.8 : The tail insertion method is used to solve the circular linked list problem of 1.7, but when the put operation is performed concurrently, data loss will occur.
load factor
  • Load factor : 0.75
  • Expansion mechanism : 0.75 * 16=12, when the capacity reaches 12, the expansion operation will be performed.
  • Reason : According to the Poisson distribution, when the load factor is 0.75, the space utilization rate is relatively high, and the frequency of hash collision is less, which belongs to the optimal size of time and space balance.
put operation sequence

1. First judge whether the array is empty, if it is empty, call resize() to expand, and directly insert into the corresponding array.
2. If it is not empty, calculate the index value of the data based on the current key to determine whether the current key exists, and if it exists, overwrite the value.
3. If it does not exist, judge whether it is a red-black tree. If it is a red-black tree structure, insert it directly.
4. If it is not a red-black tree, traverse the linked list to prepare for insertion. If the length of the linked list is less than 8 and the length of the array is less than 64, insert the linked list directly. , after the transfer is successful, insert it again.
5. Determine whether the ++size is greater than the threshold, and if it is greater, perform a resize();

ConcurrentHashMap

underlying implementation

1.7
Storage structure : Segment array + HashEntry array + linked list

Thread-safe implementation : Segment inherits ReentrantLock and is used as a segment lock. In theory, if there are n Segments, it can support concurrent access of up to n threads at the same time, thus greatly improving the efficiency of concurrent access.

Segment lock : ConcurrentHashMap is composed of multiple segments (a segment contains many Nodes), and each segment has a lock to achieve thread safety. When a thread occupies a lock to access one of the segment data, the data of other segments can also be accessed access by other threads.

1.8
Storage structure : Node array + linked list/red-black tree

Thread safety implementation : The concept of segment lock is canceled, and the synchronized keyword and CAS are used to ensure its thread safety. If CAS fails, spin guarantees success, and if it fails again, synchronized guarantees.
synchronized: Only lock the first node of the current linked list or red-black tree.

CAS(compare and swap) : A CAS operation consists of three operands—the memory location (V), the expected old value (A), and the new value (B). If the value of a memory location matches the expected original value, the location value is automatically updated with the new value. Otherwise, do nothing.


Concurrent multithreading related

synchronized keyword

effect

The synchronized keyword is used to prevent thread interference and memory consistency errors, and solve the consistency of resources between multiple threads.

usage
  • Modified instance method lock is the current instance object
  • The modified static method lock is the Class object of the current class
  • The modified code block lock is the object configured in the synchonized brackets
underlying principle

A Monitor is built into the object.
Monitor can be understood as a synchronization tool or a synchronization mechanism, and is usually described as an object. Every Java object has an invisible lock called an internal lock or Monitor lock.

Objects in memory consist of three parts

They are: object header, instance data and its filling (not required).

Mark Word: It exists in the object header and stores information such as the hashcode, lock information, generational age, and GC flag of the object. The process of lock upgrade is realized based on modifying the Mark Word.

How to implement synchronization
Synchronization method : It is implicit and does not need to be controlled by bytecode instructions. It is judged whether a method is declared as a synchronization method through the ACC_SYNCHRONIZED access flag.
Synchronization code block : Synchronization is achieved through two instructions, monitorenter and monitorexit , which are associated with a monitor object. When entering, set the Owner as the current thread, enter the counter +1, and exit the counter -1.

lock escalation process

Process: no lock status - > partial lock status (1 CAS) -> lightweight lock status (multiple CAS) -> heavyweight lock
status The process of converting to fewer coarse-grained locks to reduce system overhead and reduce performance consumption caused by locks.

volatile keyword

characteristic

Volatile is a lightweight synchronization mechanism provided by Java

  • Guaranteed visibility (JMM model and MESI protocol)
  • atomicity not guaranteed
  • Prohibition of instruction rearrangement (based on memory barrier implementation)
MESI agreement

A cache coherence protocol, mainly to solve the problems of slow multi-core CPU access to memory and cache inconsistency.

state describe
M(Modified) The data has been modified and is inconsistent with the data in the memory, and the data only exists in this Cache
E(Exclusive) The data is consistent with the data in the memory, and the data only exists in this Cache.
S(Shared) The data is consistent with the data in the memory, and the data exists in many caches.
I(Invalid) The contents of the cache line are not valid.
JMM memory model

1. All variables are stored in the main memory, and each thread has a private working memory to store a copy of the shared variables, and each thread can only access its own working memory, and cannot access the working memory of other threads. Variables in main memory cannot be read or written directly.
2. Different threads cannot directly access the variables in each other's working memory, and the variable value transfer between threads needs to be completed in the main memory.

Three characteristics in multithreaded concurrent programming
  • Visibility
    means that when multiple threads access the same shared variable, one thread modifies the value of the variable, and other threads can immediately see the modified value.
  • Atomicity
    Atomicity means that an operation or a group of operations is either executed in its entirety or not executed at all.
  • Orderliness
    Orderliness means that the order in which the program is executed is executed in the order in which the codes are executed.
bus storm

Since volatile is based on the MESI cache coherence protocol, it needs to constantly sniff from the main memory and CAS keeps looping and invalidating interactions, causing the bus bandwidth to peak.

AtomicInteger

A thread-safe int wrapper class based on volatile + CAS + Native

Lock

introduce

Lock locks are also called synchronization locks , and the implementation class is ReentrantLock.

The difference between Lock and synchronized
  • Synchronized is a keyword that acts on the JVM level, and Lock is a lock at the API level.

  • Synchronized does not need to release the lock manually, and will automatically release the lock when the thread ends or an exception occurs. ReentrantLock must manually release the lock. If an exception is encountered, an incorrect release will cause a deadlock. Generally, it is released in finally{} .

  • Synchronized is an unfair lock . ReentrantLock can be set through parameters to determine whether it is a fair lock . Whether it is fair or not depends on whether threads acquire locks in order.

  • Synchronized cannot be interrupted, and ReentrantLock can be interrupted.

  • The Condition (condition) provided by ReentrantLock can specify which threads to wake up, while synchronized can only wake up one or all of them randomly.

  • ReentrantLock is more flexible than synchronized.

ThreadLocal

introduce

The ThreadLocal class stores the private data of each thread, that is, the local variable copy of the thread, and each thread maintains its own data , so as to achieve the effect of thread isolation.

memory leak problem

The life cycle of ThreadLocalMap is consistent with that of Thread. At the same time, the key of Entry in ThreadLocalMap is a weak reference to ThreadLocal, but the value in Entry is strongly referenced by Entry. If the Entry object in ThreadLocalMap is not manually cleared, the key will be used for garbage collection. Will be recycled, but the value will be recycled, so there is a possibility of memory leaks regardless of whether weak references are used. So generally you need to manually call the remove() method to clear it after use .

Application Scenario
  • Store user information globally for easy access.
  • Instead of explicit passing of parameters.
  • Solve the problem of thread safety and achieve the effect of thread isolation.

thread

What are the ways to create threads
  • Inherit the Thread class.
  • Implement the Runnable interface.
  • Created using Callable and Future.
  • Create a ThreadPool and get it from the thread pool.
What are the states of the thread
  • New (new), the newly created thread has been initialized and entered the Runnable (ready) state;
  • Runnable (ready), waiting for thread scheduling, and enters the Running (running) state after scheduling;
  • Running (running), the thread is running normally, during which it may enter the Blocked (blocked)
    state due to certain circumstances (synchronization lock; the sleep() and join() methods are called to enter the Sleeping state; the wait()
    method is executed to enter the Waiting state, waiting Other threads notify notification wakeup);
  • Blocked (blocked), the thread suspends running, and enters the Runnable (ready) state after unblocking
    to wait for scheduling again;
  • Dead (death): The thread completes its task and ends normally or terminates due to an exception;

Thread Pool

Advantages of thread pool
  • Reduce resource consumption.
  • Improve responsiveness.
  • Improve thread manageability.
  • Avoid blocking caused by a large number of threads preempting each other for system resources.
The core parameters of the thread pool
  • corePoolSize number of core threads
  • maximumPoolSize The maximum number of threads in the thread pool
  • keepAliveTime idle thread survival time
  • unit idle thread survival time unit
  • workQueue work queue
  • threadFactory thread factory
  • handler rejection strategy
    • AbortPolicy: Discard tasks and throw RejectedExecutionException ( default )
    • DiscardPolicy: Discard tasks, but do not throw exceptions.
    • DiscardOldestPolicy: Discard the task at the head of the queue and resubmit the rejected task.
    • CallerRunsPolicy: The task is handled by the calling thread.
What are the ways to create a thread pool
Executors
  • newCachedThreadPool: Creates a cacheable thread pool.
  • newFixedThreadPool : Create a fixed-length thread pool.
  • newScheduledThreadPool : Create a fixed-length thread pool that supports timing and periodic task execution.
  • newSingleThreadExecutor : Create a single-threaded thread pool.
  • newWorkStealingPool: Creates a new thread pool with preemptive operations, and each thread has a task queue to store tasks.
ThreadPoolExecutor
  • Customize the thread pool you need according to the core parameters
How to set the number of core threads

JVM, Spring, Mysql, Redis and other related interview questions are being continuously updated.

Guess you like

Origin blog.csdn.net/weixin_40579395/article/details/124588472
Recommended