Talk about your understanding of the Java platform

Let’s start with three features of the Java language:

Cross-platform writing runs everywhere at once

The.java files that we write are compiled by javac to generate.class bytecode files that are machine-independent. Oracle officially provides different JDK versions for different operating systems for different JVM versions, .class files are loaded into memory by the JVM virtual machine, which shields memory and operating system differences.

JRE Java runtime environment JVM VIRTUAL machine Java core class library can only run Java programs JDK Java development kit JDK contains a series of development tools, such as JRE and javac compiler monitoring, debugging and tuning tools

The Spring transaction

Juejin. Cn/post / 684490…

  • ACID properties of transactions
  • The isolation level of the transaction
  • Problems with concurrent transactions
  • Propagation behavior of transactions

HTTP is different from HTTPS

HHTP often meet test questions

  • HTTP :HTTP is a “convention and specification” for transferring “hypertext” data, such as text, pictures, audio and video, between “two points” in the computer world.

  • The HTTP status code

  • GET vs. POST, security and idempotency

  • SSL/TLS

    • Mixed encryption
    • The algorithm
    • The digital certificate
  • TCP three handshakes and four waves

Establishing a TCP connection requires three handshakes. The first time the client sends a packet to the server, the server so

It takes four waves to close a TCP connection

AOP

Juejin. Cn/post / 684490…

Juejin. Cn/post / 684490…

  • JDK dynamic proxy
  • CGLIB dynamic proxy
  • AOP implements logging procedures
  • The two dynamic proxies differ
The term concept
Before Perform the enhancement before the method is called
After Perform the enhancement after the method is invoked
After-returning Perform the enhancement after the method has successfully executed
After-throwing Perform the enhancement after the method throws the specified exception
Around Perform custom enhancement behavior before and after method calls (the most flexible way)

The thread pool

Juejin. Cn/post / 684490…

www.jianshu.com/p/9710b899e…

  • Pooling technology

  • Core parameters and functions

  • How thread pools work

  • There are four rejection strategies

  • There are three exception handling methods in the thread pool

  • The work queue of the thread pool

  • Several common thread pools

  • Thread states (6 types)

Thread status Thread status

HashMap

  • The data structure
  • The important parameters
  • The constructor
  • Put method parsing
  • Index calculation
  • Expansion mechanism

mysql

Back table queries and overwrites indexes

  • Query back to the table (If the query field is not in the index, locate the row record using the primary key value first, which is slower than directly querying the index tree to locate the row record.)
  • Overwrite indexes (you can retrieve all the column data required by SQL from a single index tree, and do not need to return to the table, which is faster than returning to the table. Build the queried field into the joint index)
  • The index B + tree
  • Slow query optimization Common slow query optimization
  • Clustered indexes and non-clustered indexes

Slow query optimization

Details how to optimize slow queries? Add an index to a table if there is no index in the table, consider creating an index on the columns involved in WHERE and Order by. If an index is added, check whether it is invalid. The common causes of index failure are as follows:

  • If the or keyword is used, no index is added to the field. If the index fails, full table scan is performed
  • The index will be invalidated if the index begins with % and the index ends with %
  • If there is a mathematical operation on the index column in the WHERE condition, the index is invalid.
  • Try to avoid functional manipulation of fields in the WHERE clause, which will cause the engine to abandon indexes for full table scans
  • After creating an index for multiple fields, for a multi-column index, the index will only be used if the query condition uses the first of those fields, the left-most matching principle.
  • Avoid null values for fields in the WHERE clause, which would cause the engine to abandon the index and perform a full table scan.
  • Use in where clauses should be avoided! = or <> otherwise the engine will abandon the index for a full table scan

Query the amount of data is too large (you can use multiple queries, other methods to reduce the amount of data) can use multithreading, segmented query returned unnecessary rows and columns, as little as possible to use SELECT *, query as far as possible to select the field, useless field do not find out as much as possible to use digital fields, Because the mysql engine compares strings one by one, it is more efficient to compare numbers only once. Table is cut horizontally and vertically to reduce the complexity and data size of the table. The index

Index failure condition

Use the OR condition to add fields that have no index. (Full table scan is performed for fields that have no index.) When you write an SQL statement, use single quotation marks for fields that are of the string type. (This is because, without single quotes, strings are compared to numbers, and they do not match. MySQL does an implicit type conversion to convert them to floating point numbers for comparison.) Select * from ‘%’ where ‘%’ = ‘%’; Index (k1,k2,k3) : (k1,k2,k3) : (k1,k2,k3) : (k1,k2,k3) : (k1,k2,k3) : (k1,k2,k3) (k1), (k1,k2), and (k1,k2,k3). This is the left-most matching principle. The index k1 is searched first, and if k1 does not exist, it cannot be searched as an index. Index failure using (! If = or < >, not in), the index is invalid. If is null is not null is used on an index field, the index may become invalid. If mysql has a small amount of data, it is estimated that full table scan is faster than index scan, so index is not used. Mysql index leftmost matching principle? For example, when a joint index (a, B, C) is created, mysql will compare a,b, and c according to the joint index field from left to right. If mysql does not use the first field of the joint index in the query, then it will not be able to compare a,b, and c. Then the joint index will be invalid.

Why does indexing optimize slow queries? Since an index is a data structure that improves query speed, Mysql indexes are implemented using B+ tree, which is a multi-way balanced search tree to improve search speed. There are also structures that can improve query speed, hash tables, balanced binary trees, B trees, etc.

The JVM virtual machine

  • Memory region parsing
  • Garbage collection mechanism
  • Garbage collector 7 kinds

CMS Garbage Collector G1 Garbage collector

  • Garbage collection algorithms [juejin.cn/post/684490…]
  • Parents delegate mechanism [www.jianshu.com/p/1e4011617]…

Garbage collector

[juejin. Cn/post / 684490…].

  • Serial (single thread, new generation, copy algorithm)
  • Parallel New (Multithreading, New generation, copy algorithm, time first)
  • Insane (Multi-threaded, next-generation, copy algorithm, throughput first)
  • Serial Old (single thread, Old generation, mark clear)
  • Prallel Old, gradient Old, tag clearing
  • CMS: Garbage collector and application parallel (multithreading, old generation, tag cleaning) are cleaned twice, the first time to clean, the worker thread and garbage thread parallel, the second STW. (Java 9 was abolished)
  • G1 (Cenozoic + Old Generation)

CMS processes initial tokens, which cause STW, reachability analysis to find concurrent tokens of objects directly associated with GCroot, run concurrently with the user thread, and iterate through all garbage in heap memory. Pre-clean, run at the same time as the user thread; Terminable pre-cleaning, running at the same time as the user thread; Re-marking, which results in SWT; Concurrent cleanup, running at the same time as the user thread;

The lock

  • The mutex
  • spinlocks
  • Read-write lock
  • Pessimistic locking
  • Optimistic locking

A distributed lock

How to ensure idempotency of interfaces

To solve the problem

  • The front end repeatedly submits the form
  • Users brush orders maliciously
  • The interface was submitted repeatedly due to timeout
  • Repeated message consumption

Refer to the article

  • Reference Article 1
  • Reference Article 2

Summary of interface idempotent solutions

  • Database unique primary keys (unique indexes) use distributed ids as primary keys to ensure global uniqueness of ids
  • Pessimistic lock database row lock InnoDB engine
  • Optimistic lock version Version number
  • The state machine determines that the number of rows affected by the order status and updateSql statement is 0
  • The downstream generates a distributed ID to initiate a request, and the server determines repeated requests in combination with setNx
  • Duplicate Token Token

How to ensure data consistency between the cache and the database in dual write

redis

Interview questions redis

  • Underlying data types
  • The single thread model (epoll multiplexing IO technology www.cnblogs.com/yrjns/p/125…
  • Expired key value deletion policy
  • Key value elimination strategy
  • The cache to penetrate
  • Cache breakdown
  • Cache avalanche
  • A master-slave replication
    • Replication mechanism (Full replication incremental replication)
    • Replication principle (version number pseudo-random string + offset to measure data changes)
  • The guard mode
    • Monitor node status
    • Notify other nodes of failures
    • Failover (Confirm that the master is offline, disconnect the master from other slaves, confirm that a new master is connected)

Database read/write separation

Data read and write separation & database and table

  • Read-write separation
  • shardingJdbc
  • Principle of primary/secondary database replication
  • Problems with read/write separation

JVM 1.7 differs from 1.8 memory

JVM Interview Question 2

Jdk1.7 heap memory

  • Young, Young generation

Young zone is divided into three parts, Eden zone and two Survivor zones of strictly the same size. In Survivor zone, only one of them is used at a certain time, and the other one is reserved for copying objects in garbage collection. When Eden zone becomes full, The GC will then move the surviving objects to the free Survivor zone, and after several garbage collections, the surviving objects will be moved to the Tenured zone, according to JVM policy.

  • Tenured old s

A Tenured region is an area in which objects with a long life span will be moved to a Tenured region. If an application-level cache is used, objects in the cache will be moved to a Tenured region.

  • Perm permanent generation

The Perm generation mainly stores class, method and filed objects. The space of these parts will not overflow unless a lot of classes are loaded at one time. However, in the case of application servers with hot deployment, Sometimes meet Java. Lang. OutOfMemoryError: PermGen space mistake, a big cause of this error could be redeployed every time, but again after deployment, the class of a class is not uninstall, this creates a lot of class object stored in Perm, In this case, restarting the application server generally resolves the problem.

Virtual

The difference between the maximum memory and the initial memory is the Virtual area.

Jdk1.8 heap memory

As you can see from the figure above, the JDK1.8 memory model is composed of two parts, from young to + old.

  • Young generation: Eden + 2 * Survivor.

  • Old age: OldGen.

Regional scale division

New Generation: Eden S0 S1 =8:1:1 in old age 1:2 New generation

The biggest change in jdk1.8 is the Perm area, which has been replaced with Metaspace(metadata space). Note: Metaspace is not in the virtual machine, but in local memory, which is the biggest difference from the permanent generation of 1.7.

In real use, due to the permanent generation memory often enough or memory leaks occur, exceptions: Java. Lang. OutOfMemoryError: PermGen. Based on this, the permanent generation is deprecated in favor of meta-space, using local memory space instead. Similar in nature to permanent generations, meta-spaces are implementations of method areas in the JVM specification. However, the biggest difference between a meta-space and a permanent generation is that the meta-space is not in the virtual machine, but uses local memory. Therefore, by default, the size of a meta-space is limited only by local memory, but you can specify the size of a meta-space with the following parameters:

The JVM tuning

Why JVM tuning

How to keep thread safe

Thread safety generally considers three aspects to ensure atomic visibility and order of the memory model

atomic

To ensure atomicity of code execution, use synchronized and Lock to ensure atomicity of the whole block of code. The thread must flush the value of I back to main memory before releasing the lock.

visibility

Java uses volatile to provide visibility. When a variable is volatile, changes to it are immediately flushed to main memory, and when other threads need to read the variable, the new value is read from memory. Ordinary variables do not guarantee this.

Realize the principle of

  • Instructions prefixed with Lock cause the processor cache to be written back to memory;
  • Writing one processor’s cache back to memory causes other processors’ caches to be invalidated.
  • When the processor finds that the local cache is invalid, it rereads the variable data from memory to get the latest value.

order

The JMM allows the compiler and processor to reorder instructions, but specifies the as-if-Serial semantics, meaning that no matter how reordered, the execution result of the program cannot be changed. So when I read a variable, I can always read its latest value, which means that whatever other thread writes to that variable is immediately updated to main memory, and I can read the value that I just wrote from main memory. That is, the volatile keyword guarantees visibility and order.

The volatile keyword

Volatile Interview details

Volatile has two main characteristics

Shared variables that are volatile have two characteristics: 1. The memory visibility of operations on this variable is guaranteed without multithreading. To ensure the visibility of memory, we must first explain the JMM memory model. What threads operate is to copy variables in main memory to the working memory, modify the copied variables and write them back to main memory. As a result, in the case of multi-threading, each thread operates on its own copy of variables, and there is invisibility of main memory variables. The Volatile keyword ensures that changes to a variable copy are flushed to main memory as soon as possible. It ensures that changes to a variable copy are visible in main memory. 2. Disallow instruction reordering. JMM allows the compiler and processor to reorder instructions, but specifies the as-if-serial semantics, meaning that no matter how the program is reordered, the execution result cannot be changed. Happens-before principle;

The underlying implementation mechanism for volatile

If you generate assembly code for both volatile and non-volatile code, you will find that volatile code has an extra lock prefix. The LOCK prefix directive actually acts as a memory barrier that provides the following functions:

  • The JVM cannot reorder subsequent instructions to places in front of the memory barrier
  • Write a copy of the volatile modified modified variable in the memory, CPU, cache coherence protocol, each processor by sniffing the spread of the data on the bus to check the value of the cache is expired, when the processor found himself cache variables corresponding to the memory address has been changed, and will be set for the current processor cache line in invalid state,

Examples of using volatile

Implementation of singleton Pattern, Typical Double-checked Locking (DCL)

Strong reference, soft reference, weak reference, phantom reference, reference queue summary

Refer to summary

Strong reference

  • Object Object = new Object(); The JVM would rather throw an OutOfMemoryError (OOM) runtime error that causes the program to abort than randomly recycle “alive” objects with strong references to solve the memory problem. An ordinary object can be collected by the garbage collector (depending on the garbage collection policy) if no other reference relationship exists, as long as the scope of the reference is exceeded or the corresponding strong reference is explicitly set to NULL.

Reference (Reference class)

  • SoftReference, WeakReference, and PhantomReference are all subclasses of java.lang.ref.Reference, which has four methods

void clean(); Clear this reference object. (This method is called only by Java code; When the garbage collector clears the reference, it executes directly without calling this method. boolean enqueue(); Add this reference object to its registered queue, if any. T get(); Returns an indication of this reference object. (This method can be used to return the object referenced by Reference, which can be changed back to a strong Reference.)

SoftReference

  • A SoftReference is implemented using SoftReference. Soft references have a shorter lifetime than strong references. Only if the JVM thinks it is out of memory will it attempt to reclaim objects pointed to by soft references: that is, the JVM ensures that objects pointed to by soft references are cleaned up before outofMemoryErrors are thrown. A soft Reference can be used in conjunction with a Reference queue (ReferenceQueue). If the object referenced by the soft Reference is collected by the garbage collector, the Java virtual machine will use the soft Reference as a Reference. Not referring to the referenced object) joins the reference queue associated with it. Later, we can call the poll() method of ReferenceQueue to check if any of the objects it cares about have been reclaimed (because references in the queue point to objects that have been reclaimed). If the queue is empty, a NULL is returned, otherwise the method returns the previous Reference object in the queue.

  • Application scenario: Soft references are used to implement memory sensitive caches. If you have free memory, you can keep the cache for a while and clean it up when you run out of memory. This ensures that you don’t run out of memory while using the cache.

WeakReference

  • WeakReference is implemented through the WeakReference class. Weak references have a shorter lifetime than soft references. When the garbage collector thread scans the memory area under its control, once it finds an object with weak references, it reclaims its memory regardless of whether the current memory space is sufficient or not. Because the garbage collector is a low-priority thread, it is not necessarily quick to reclaim weakly referenced objects. A weak reference can be used in conjunction with a ReferenceQueue (ReferenceQueue), and if the object referenced by a weak reference is garbage collected, the Java virtual machine adds the weak reference to the ReferenceQueue associated with it (using soft references with reference queues as above).

  • Application scenario: Weak applications can also be used for memory sensitive caches.

Virtual Reference

  • Virtual references, implemented through the PhantomReference class. You cannot access any properties or functions of an object through a virtual reference. Phantom references just provide a mechanism to make sure that objects do something when they are finalize. If an object holds only virtual references, it can be collected by the garbage collector at any time, just as if there were no references at all. A virtual reference must be used in conjunction with a ReferenceQueue. When the garbage collector is about to reclaim an object and finds that it has a virtual reference, it adds the virtual reference to the reference queue associated with it before reclaiming the object’s memory. A program can determine whether a referenced object is about to be garbage collected by determining whether a virtual reference has been added to the reference queue. If a program finds that a virtual reference has been added to the reference queue, it can take some program action (using soft and weak references with reference queues as above) before the referenced object’s memory is reclaimed.

  • Application scenario: It can be used to track the activity of objects being collected by the garbage collector. A system notification will be received when an object associated with a virtual reference is collected by the garbage collector

JDBC Connection Procedure

BIO NIO AIO

Juejin. Cn/post / 695908… The address space of a process is divided into user space and kernel space. Applications like ours run in user space, and only kernel space can perform system-level resource-related operations such as file management, process communication, memory management, and so on. In other words, if we want to do IO operations, we must depend on the capacity of the kernel space. Our application makes IO calls (system calls) to the operating system’s kernel, and the operating system’s responsible kernel performs specific IO operations.

BIO Blocking IO

In the synchronous blocking IO model, after an application makes a read call, it blocks until data is copied to user space in the kernel.

NIO synchronizes non-blocking IO

In the synchronous non-blocking IO model, applications make read calls and wait for data to be copied from kernel space to user space, while threads remain blocked until data is copied from kernel space to user space. Compared with synchronous blocking IO model, synchronous non-blocking IO model avoids continuous blocking through polling operation.

AIO Asynchronous I/O model

Asynchronous IO is implemented based on events and callbacks, meaning that an action is applied and returned, not blocked, and when the background processing is complete, the operating system notifies the appropriate thread to proceed with the subsequent action.

conclusion

WebSocket

HTTP is a half-duplex communication protocol. Only the client requests data to the server, and the server returns the request data to the client. The server cannot actively push data. WebSocket implements full duplex communication, which is based on TCP transport protocol and multiplexes HTTP handshake channel. Allows the server to send data to the client actively, establishes a long-term connection between the client and the server, and both sides can send data at will. Strong real-time performance can be used to do QQ and wechat. After the client and server connection is created, the packet header is less and the control overhead is great.

Difference between HashMap and Hashtable

A HashMap can be almost equivalent to a Hashtable, except that a HashMap is non-synchronized and can accept NULL (a HashMap can accept null keys and values, whereas a Hashtable cannot).

ConcurrentHashMap

The put method is unsafe. Data inconsistency occurs when multiple threads put the same data. Data inserted by THREAD A and thread B may disappear.

ConcurrentHashMap

Segment[] : Segment[]; Segment[] : Segment[]; Each Segment is a HashEntry[] array Segment that inherits ReentrantLock. The Segment’s put method is tryLock unlock

Put (CAS) + Synchronized + Node + Unsafe

The difference between abstract classes and interfaces

First of all to say the difference of purpose Abstract class is to abstract things, the interface is to abstract ability/behavior The difference on the grammar An abstract class is a single inheritance interface can realize more abstract classes and interfaces can be instantiated, the common method of abstract classes can be included in the abstract, is all the interface methods must be abstract, cannot have the common method of the abstract.

group by having limit order by

Group by having further filters the results of where and Group by processing to get the data we want

Mysql > alter database

  • Left JOIN Returns records that include all the records in the left table and the join fields in the right table equal to each other.
  • The right Join returns a record that includes all the records in the right table equal to the join fields in the left table.
  • An inner join returns only rows in which the join fields in the two tables are equal.
  • To heavy distinct

How to locate a build environment problem

Common sorting algorithms

  • Selection sort
  • Bubble sort
  • Quick sort
  • Heap sort

The creation of a String object

String s1 = “abc”; Determines whether the string object exists in the string constant pool. If it does not, create an object in the string constant pool and reference it to S1

String s = new String(“abc”); If the string constant pool does not exist, the string constant pool (created when the compiler parses the class file) and new objects in the heap (the new keyword is created in the heap) are not created in the string constant pool, but a new object is still created in the heap

When String s = new String(” ABC “); The JVM first checks for the existence of the String object “ABC” in the String Pool. If it does not exist, it creates a new String object “ABC” in the String Pool and executes the new String(” ABC “) constructor. Create a new string object “ABC” in the Heap (new objects are placed in the Heap) and reference S to the new object created in the Heap; If the object already exists, instead of creating a new String object “ABC”, we use the existing object “ABC” in the String Pool, and then execute the new String(” ABC “) constructor to create a new String object “ABC” in the Heap. And points the reference S to the new object created in the Heap.

Process of creating a class in memory

JUC

Several ways to create threads

Thread creation

  1. Inherits Thread and overwrites the run() method
  2. The Runnable interface can be implemented in multiple ways
  3. Implementing the Callabe interface can retrieve the resulting futureTask of thread execution
  4. Thread pools create threads

Design patterns

Simple Factory Factory pattern Abstract factory pattern

Simple Factory Factory pattern Abstract factory pattern

Simple Factory model

  • An abstract product class, a concrete product class, and a factory hand over instantiation of the class to the factory for easy decoupling.

Factory method pattern

  • The open closed principle is implemented – no changes to the original code are required each time a child product is added
  • Multiple specific factories – one specific factory for each specific product

Abstract Factory pattern

  • Concrete factory class – Generates (a set of) concrete products
  • Implementation of multiple product families (families of related products), while the factory approach pattern of a single product, can meet more production needs

Why use a red-black tree instead of a normal binary balanced tree