A selection of Java technical interview questions from Alibaba, Huawei, Tencent, JD.com, and Baidu

What is the class loading mechanism of the VM? What are the implementation methods?
Class loading mechanism:

Class loading refers to reading the binary data in the .class file of the class into memory, placing it in the method of the runtime data area, and then creating a java.lang.Class object in the heap area for A data structure encapsulated within a method area. The loading of the class is ultimately the Class object in the heap area. The Class object encapsulates the data structure of the class in the method area and provides Java programmers with an interface for accessing the data structure in the method area.

If you also want to get a high salary in the IT industry, you can participate in our training camp courses, choose the most suitable course for you, and teach yourself the technical masters. After 7 months, you can enter a famous company and get a high salary. Our course content includes: Java engineering, high performance and distributed, high performance, simple language. high architecture. Performance tuning, Spring, MyBatis, Netty source code analysis and big data and other knowledge points. If you want to get a high salary, want to study, want a good job prospect, want to gain an advantage in competition with others, want to enter Ali for an interview but are worried that the interview will fail, you can come. The group number is: 697579751

There are three ways of class loading:

1) When the command line starts the application, it is initialized and loaded by the JVM

2) Dynamic loading through the Class.forName() method

3) Dynamic loading through the ClassLoader.loadClass() method

Common garbage collection algorithms for JVM?
1) Mark-clear algorithm: All objects that need to be recovered at the front and rear line markers are uniformly recovered after the marking is completed.

2) Copy algorithm: divide the available memory into two equal-sized blocks according to their capacity, and only use one of them at a time. When a piece of memory is used up, store it on another piece, and then clean up the used memory space at one time.

3) Mark-to-clean algorithm: The marking process is the same as the "mark-to-clean" algorithm, but the subsequent steps are not to directly clean up the recyclable objects, but to move the end of the object, and then directly clean up the memory beyond the end boundary.

4) Generational collection algorithm: Generally, the Java heap is divided into the new generation and the old generation, and the most appropriate collection algorithm is adopted according to the characteristics of each generation. The new generation found that a large number of objects died, and the replication algorithm was used. Because of the high survival rate of objects in the old age, the "mark-sweep" or "mark-clean" algorithm must be used for recycling.

What are the common command line tools for JVM tuning? What are the common tuning parameters of JVM?
(1) Common command tools for JVM tuning include:

1) The jps command is used to query the running JVM process,

2) jstat can display data such as class loading, memory, garbage collection, JIT compilation, etc. in the local or remote JVM process in real time

3) jinfo is used to query the values ​​of properties and parameters of the currently running JVM.

4) jmap is used to display the details of the current Java heap and permanent generation

5) jhat is used to analyze dump files generated by jmap, which is a tool that comes with JDK

6) jstack is used to generate snapshots of all threads of the current JVM. Thread snapshots are the method that each thread of the virtual machine is executing, and the purpose is to locate the reason for the long pause of the thread.

(2) Common tuning parameters of JVM include:

-Xmx

  Specify the maximum heap memory of the java program, use java -Xmx5000M -version to determine the maximum heap memory that the current system can allocate

-Xms

  Specify the minimum heap memory, usually set to the same as the maximum heap memory, reducing GC

-Xmn

  Set the young generation size. Whole heap size = young generation size + old generation size. So after increasing the young generation, the size of the old generation will be reduced. This value has a great impact on system performance, and Sun officially recommends setting it to 3/8 of the entire heap.

-Xss

  Specifies the maximum stack space of the thread. This parameter determines the depth of the java function call. The larger the value, the deeper the call depth. If the value is too small, it is easy to pop out the stack overflow error (StackOverflowError)

-XX:PermSize

  Specifies the initial value of the method area (permanent area), the default is 1/64 of the physical memory, removed in the Java8 permanent area, and replaced by the metadata area, specified by -XX:MetaspaceSize

-XX:MaxPermSize

  Specify the maximum value of the method area, the default is 1/4 of the physical memory. In java8, the size of the metadata area is specified by -XX:MaxMetaspaceSize

-XX:NewRatio=n

  The ratio of the old generation to the young generation, -XX:NewRatio=2, means that the ratio of the old generation to the young generation is 2:1

-XX:SurvivorRatio=n

  The size ratio of the Eden area and the Survivor area, -XX:SurvivorRatio=8 means that the size ratio of the Eden area and the Survivor area is 8:1:1, because the Survivor area has two (from, to)

What is the locking mechanism of ConcurrentHashMap, please explain in detail?
The reason why the HashTable container is inefficient in a highly competitive concurrent environment is because all threads accessing the HashTable must compete for the same lock. If there are multiple locks in the container, each lock is used to lock part of the data in the container. , then when multiple threads access data in different data segments in the container, there will be no lock competition between threads, which can effectively improve the efficiency of concurrent access. This is the lock segmentation technology used by ConcurrentHashMap. First, the data is divided into segments storage, and then assign a lock to each segment of data. When a thread occupies the lock to access one segment of data, other segments of data can also be accessed by other threads.

Introduction to the G1 collector? And what about its memory partitioning?
(1 Introduction:

Garbage-First (G1, garbage first) collectors are service-type collectors that target multiprocessor machines, large memory machines. It is highly consistent with the goal of garbage collection pause time while achieving high throughput. Oracle JDK 7 update 4 and later releases fully support the G1 garbage collector

(2) The memory division method of G1:

It divides the heap memory into multiple heap areas of equal size, each of which is a logically continuous piece of memory (virtual memory). Some of these areas are used as the same role as the old generation collector (eden, survivor, old), but the number of regions for each character is not fixed. This provides more flexibility in memory usage

What conventions need to be followed when overriding the equals method?
When overriding the equals method, you need to follow general conventions: reflexivity, symmetry, transitivity, consistency., non-nullability

1) Reflexivity

For any non-null reference value x, x.equals(x) must return true. ---This is basically no problem

2) Symmetry

For any non-null reference values ​​x and y, y.equals(x) is also true if and only if x.equals(y) is true.

3) Transitivity

For any non-null reference value x, y, z. If x.equals(y)==true, y.equals(z)==true, then x.equals(z)==true.

4) Consistency

For any non-null reference values ​​x and y, multiple calls to x.eqals(y) will consistently return true, or consistently return false, as long as the information used by the equals comparison operation on the object has not been modified.

5) Non-empty

All compared objects cannot be null.

A brief introduction to the optimized lock mechanism of Synchronized, including spin locks, biased locks, lightweight locks, and heavyweight locks?
Spinlock:

To put it bluntly, the thread spin is to make the cup do useless work. For example, it can execute several for loops, and can execute several empty assembly instructions. The purpose is to occupy the CPU and wait for the opportunity to acquire the lock. If the rotation time is too long, it will affect the overall performance, and if the time is too short, the purpose of delay blocking will not be achieved.

Bias lock

Biased lock means that once the thread obtains the monitoring object for the first time, then the monitoring object is "biased" to the thread, and subsequent calls can avoid CAS operations.

To put it bluntly, it is to set a variable. If it is found to be true, there is no need to go through various locking/unlocking processes.

Lightweight lock:

Lightweight locks are upgraded by bias. When a thread enters a synchronized block, biased locks are upgraded to lightweight locks when a second thread joins the lock contention.

heavyweight lock

The weight lock is also called the object monitor (Monitor) in the JVM. It is very similar to the Mutex in C. In addition to the function of Mutex (0|1) mutual exclusion, it is also responsible for implementing the function of Semaphore (semaphore), which is It is said that it contains at least a queue for competing locks, and a signal blocking queue (wait queue), the former is responsible for mutual exclusion, and the latter is used for thread synchronization.

Comparison of biased locks, lightweight locks, and heavyweight locks:

The difference between Redis and Memcache? How to choose these two technologies?
the difference:

1) Redis and Memcache both store data in memory, both are in-memory databases. But memcache can also be used to cache other things, such as pictures, videos, etc.

2) Redis not only supports simple k/v type data, but also provides storage of data structures such as list, set, and hash.

3) Virtual memory -- When Redis runs out of physical memory, it can swap some values ​​that have not been used for a long time to disk

4) Expiration policy --memcache is specified at the time of set, such as set key1 0 0 8, that is, it will never expire. Redis can be set by e.g. expire, e.g. expire name 10

5) Distributed - set up memcache cluster, use magent to be one master and multiple slaves; redis can be one master and multiple slaves. can be master and slave

6) Storage data security -- after memcache hangs, the data is gone; redis can be regularly saved to disk (persistence)

7) Disaster recovery -- after memcache hangs, the data cannot be recovered; after redis data is lost, it can be recovered through aof

8) Redis supports data backup, that is, data backup in master-slave mode.

Selection:

If you simply access data such as key-value, it is better to use memcache

If you want to support data persistence, multiple data types (such as sets, hashes, etc.), and use list types for advanced applications such as queues, use redis

What is the persistence mechanism of Redis? Advantages and disadvantages of each?
Redis provides two persistence mechanisms, RDB and AOF.

1) RDB persistence method:

It refers to recording all key-value pairs of the redis database in the form of dataset snapshots.

advantage:

  1. There is only one file dump.rdb, which is convenient for persistence.

  2. Good disaster tolerance, a file can be saved to a safe disk.

  3. To maximize performance, fork the child process to complete the write operation, and let the main process continue to process commands, so IO is maximized.

  4. Compared with the large data set, the startup efficiency is higher than that of AOF.

shortcoming:

  1. Low data security.

2) AOF persistence method:

It means that all command line records are saved as aof files in the format of the redis command request protocol.

advantage:

  1. Data security, aof persistence can configure the appendfsync attribute, there is always, every time a command operation is performed, it is recorded in the aof file once.

  2. By writing files in append mode, even if the server goes down in the middle, the data consistency problem can be solved by the redis-check-aof tool.

  3. The rewrite mode of the AOF mechanism.

shortcoming:

  1. The file will be larger than the file in RDB format.

  2. When the data set is large, the startup efficiency is lower than that of rdb.

Mysql database table lock, row lock, page level lock?
At the table level, directly lock the entire table. During your lock period, other processes cannot write to the table. If you are a write lock, other processes are not allowed to read

At the row level, only the specified records are locked, so that other processes can still operate on other records in the same table.

Page-level and table-level locks are fast, but there are many conflicts, and row-level conflicts are few, but slow. So take a compromise page level, lock adjacent group of records at a time.

The four characteristics of the database, the isolation level of the database?
Four characteristics of the database:

(1) Atomicity

Atomicity means that all operations contained in a transaction either all succeed or all fail and roll back.

(2) Consistency

A transaction must be in a consistent state before and after execution.

(3) Isolation

Isolation means that when multiple users access the database concurrently, such as when operating the same table, the transaction opened by the database for each user cannot be interfered by the operations of other transactions, and multiple concurrent transactions must be isolated from each other.

4) Durability

Durability means that once a transaction is committed, changes to the data in the database are permanent.

 The isolation level of the database:

1) Serializable (serialization): It can avoid the occurrence of dirty reads, non-repeatable reads, and phantom reads. 2) Repeatable read: It can avoid the occurrence of dirty reads and non-repeatable reads. 3) Read committed (read committed): to avoid the occurrence of dirty reads. 4) Read uncommitted (read uncommitted): the lowest level, no guarantee under any circumstances.

How to ensure that the set collection does not repeat in principle

1) When adding an element to the set, if the specified element does not exist, the addition is successful. That is, if the element e1 does not exist in the set (e==null ? e1==null : e.queals(e1)), then e1 can be added to the set.

2) Specifically: when adding an element to the HashSet, first calculate the hashcode value of the element, and then use this (the hashcode of the element)% (the size of the HashMap collection) + 1 to calculate the storage location of the element, if this location If the bit is empty, add the element; if it is not empty, use the equals method to compare whether the elements are equal, and do not add if they are equal, otherwise find a space to add.

What is the main difference between HashMap and HashTable? , what is the data structure of the underlying implementation of the two?
The difference between HashMap and HashTable:

Both implement the Map interface, which maps unique keys to specific values; the main differences are:

1) HashMap is not sorted, allowing one null key and multiple null values, while Hashtable does not;

2) HashMap removes the contains method of Hashtable and changes it to containsvalue and

containsKey, because the contains method is easily misleading;

3) Hashtable inherits from Dictionary class, HashMap is the implementation of Map interface introduced by Java1.2;

4) The method of Hashtable is Synchronize, but HashMap is not. When multiple threads access Hashtable, it is not necessary to synchronize its methods, and HashMap must provide external synchronization for it. Hashtable and HashMap use roughly the same hash/rehash algorithm, so there won't be a big difference in performance.

The underlying implementation data structure of HashMap and HashTable:

The underlying implementations of HashMap and Hashtable are implemented by array + linked list structure

When will HashMap be expanded, and what is the expansion algorithm?
When will HashMap expand:

When adding elements to the container, the number of elements in the current container will be judged. If it is greater than or equal to the threshold, that is, when the length of the current array is multiplied by the value of the load factor, the capacity will be automatically expanded.

What is the scaling algorithm:

Resize is to recalculate the capacity and continuously add elements to the HashMap object. When the array inside the HashMap object cannot hold more elements, the object needs to expand the length of the array so that it can load more elements. Of course, arrays in Java cannot be automatically expanded. The method is to use a new array instead of an existing array with a small capacity.

Java's virtual machine JVM's two memories: what is the difference between stack memory and heap memory?
Java divides memory into two types: one is stack memory and the other is heap memory. The difference between the two is:

1) Stack memory: Some basic type variables and object reference variables defined in the function are allocated in the function's stack memory. When a variable is defined in a code block, Java allocates memory space for the variable in the stack. When the scope of the variable is exceeded, Java will automatically release the memory space allocated for the variable, and the memory space can be used immediately. for other purposes.

2) Heap memory: Heap memory is used to store objects and arrays created by new. Memory allocated in the heap is managed by the Java Virtual Machine's automatic garbage collector.

How are exceptions classified in Java?
Abnormal overall classification:

1) The Throwable class is defined in the Java exception structure. Exception and Error are their subclasses.

2) Exception represents an exception caused by network failure, file damage, device error, or illegal user input;

3) And Error identifies errors in the Java runtime environment, such as: JVM memory exhaustion.

What are the three paradigms often mentioned in database design?
1) First Normal Form 1NF (Atomicity of Fields)

If all field values ​​in a database table are indecomposable atomic values, it means that the database table satisfies the first normal form

2) The second normal form 2NF (the fields in the table except the primary key are completely dependent on the primary key)

The second normal form is based on the first normal form. The second normal form has two important points: (1) the table must have a primary key; (2) other non-primary attributes must completely depend on the primary key, not only a part of the primary key (mainly for the joint primary key).

3) The third normal form 3NF (the fields in the table except the primary key are all directly dependent and cannot be transitive dependencies)

It cannot be a transitive dependency, that is, it cannot exist: the non-primary key column A depends on the non-primary key column B, and the non-primary key column B depends on the primary key. The key points of the distinction between the second normal form and the third normal form: 2NF: whether the non-primary key column depends entirely on the primary key, or depends on a part of the primary key; 3NF: whether the non-primary key column directly depends on the primary key, or directly depends on the non-primary key column.

How many types of thread pools are there in Java?
Java four thread pools

The first: newCachedThreadPool

  Create a thread pool that creates new threads as needed, but reuses previously constructed threads as they become available.

The second: newFixedThreadPool

  Create a thread pool with a specified number of worker threads

The third type: newScheduledThreadPool

Creates a thread pool that can schedule commands to run after a given delay or to execute periodically.

Fourth: newSingleThreadExecutor

  Create an Executor that uses a single worker thread to run the thread in an unbounded queue.

The difference between volatile and synchronized

Introduction to volatile and synchronized:

In Java, in order to ensure the consistency of data when multi-threaded reading and writing data, two methods can be used:

  1) Use the synchronized keyword

  2) Use the volatile keyword: Summarize volatile in one sentence, which enables other threads to know as soon as possible when the value of a variable changes.

The difference between the two:

1) The essence of volatile is to tell the jvm that the value of the current variable in the register is uncertain and needs to be read from the main memory, while synchronized locks the current variable, only the current thread can access the variable, and other threads are blocked.

2) volatile can only be used at the variable level, and synchronized can be used in variables and methods.

3) volatile can only achieve the modification visibility of variables, while synchronized can guarantee the modification visibility and atomicity of variables.

4) volatile will not cause thread blocking, while synchronized may cause thread blocking.

Features of Spring

1. Convenient decoupling and simplified development

Through the IoC container provided by Spring, we can hand over the dependencies between objects to Spring for control, avoiding excessive program coupling caused by hard coding.

2. AOP programming support

Aspect-oriented programming is facilitated through the AOP function provided by Spring.

3. Declare support for things

In Spring, we can be freed from the monotonous and boring transaction management code, and flexibly manage transactions in a declarative way to improve development efficiency and quality.

4. Convenient program testing

Almost all testing work can be done in a non-container-dependent programmatic way. For example, Spring supports Junit4, and Spring programs can be easily tested through annotations.

5. Easy to integrate various excellent frameworks

Spring does not exclude various excellent open source frameworks. On the contrary, Spring can reduce the difficulty of using various frameworks. Spring provides direct support for various excellent frameworks (such as Struts, Hibernate, Hessian, Quartz).

6. Reduce the difficulty of using the Java EE API

Spring provides a thin encapsulation layer for many difficult-to-use Java EE APIs (such as JDBC, JavaMail, remote calls, etc.). Through Spring's simple encapsulation, the difficulty of using these Java EE APIs is greatly reduced.

Application scenarios of spring aop:

AOP is used to encapsulate cross-cutting concerns, which can be used in the following scenarios

Authentication permission

Caching

Context passing content passing

Error handling

Lazy loading

Debugging

logging, tracing, profiling and monitoring

Performance optimization

Persistence persistence

Resource pooling Resource pooling

Synchronization

Transactions

The difference between # and $ in Mybaits

1) ${} is a variable placeholder in the Properties file, which can be used for label attribute values ​​and inside SQL, and belongs to static text replacement. For example, ${driver} will be statically replaced with com.mysql.jdbc.Driver.

2) #{} is the parameter placeholder of sql, Mybatis will replace #{} in sql with the ? sign, and will use the parameter setting method of PreparedStatement before executing sql, and set the ? sign placeholder of sql in sequence Parameter values, such as ps.setInt(0, parameterValue), and #{item.name} are obtained by using reflection to obtain the name attribute value of the item object from the parameter object, which is equivalent to param.getItem().getName().

What are the ways to sort? Please list. Implement a quick sort in JAVA.

The sorting methods are:

Insertion sort (direct insertion sort, Hill sort), exchange sort (bubble sort, quick sort), selection sort (direct selection sort, heap sort), merge sort, allocation sort (bin sort, radix sort);

Pseudocode for quicksort:

//sort a[ 0 :n- 1 ] using the quicksort method

Select an element from a[ 0 :n- 1 ] as middle, which is the pivot point;

Divide the remaining elements into two segments left and right, so that the elements in left are all less than or equal to the pivot point,

And the elements in right are all greater than or equal to the fulcrum;

Recursively sort left using the quicksort method;

Recursively use the quicksort method to sort right;

The result is left + middle + right.

The Java code implementation of quick sort is as follows:

Java Architecture/Distributed: 697579751 (Daniel Exchange Group)


Author: JDX Love Learning
Link: https://juejin.im/post/5a6993b96fb9a01c99510130
Source: Nuggets
The copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

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