Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the Java interview questions of P6?

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the P6 level Java interview questions, which have a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

1. String stringBuffer and stringBuilder

String: suitable for a small number of string operations, a string constant, that is, once an object is created, the object is immutable.

StringBuffer: suitable for multithreaded character buffers that perform a large number of operations. Belongs to thread safety.

StringBuilder: suitable for situations where a large number of operations are performed in a character buffer in a single thread. Belonging to thread is not safe.

Both StringBuffer and StringBuilder are string variables, and the object is a variable, that is, it can be changed. All aspects of StringBuilder are not modified by synchronized, and it is more efficient than StringBuffer.

Second, the underlying implementation principle of HashMap

HashMap underlying is an array + linked list implementation, it is an array of entry class, entry contains key and value values, allowing key, value can be null, through the key hashcode calculation in the location of this array, traverse the linked list to query the value, hashMap default initialization container size of 16, and then expanded to twice the original size. Belongs to thread unsafe.

In JDK1.7 and before, HashMap maintains key,value and hash and next pointers in Entry,Entry, and the entire HashMap is actually an array of Entry.

When you put a pair of keys to a HashMap, it calculates a location based on the hashCode value of the key, which is where the object is going to be stored in the array.

If no object exists at that location, put the object directly into the array If an object already exists at this location, start searching along the chain of the existing object (in order to determine whether the value is the same, map does not allow duplicate key-value pairs). If there is an object in this chain, compare it with the equals method. If the equals method of each object on this chain is more false, put the object in the array. Then link the object that previously existed at that position in the array to the back of the object.

The get method is similar, taking hash through key to find a location in the array, and then iterating through each Entry on the array until the key value equals is returned.

If the Hash collision is serious, then the implementation performance in JDK1.7 is very poor, because each insert has to traverse the complete chain to see whether the key value is repeated, and each get has to traverse the entire chain. In JDK1.8, because the search complexity of the linked list is O (n), and the search complexity of the red-black tree is O (logn), JDK1.8 uses the linked list / red-black tree to achieve HashMap, when the linked list reaches a certain threshold, the linked list is converted to a red-black tree.

Third, the difference between HashMap and ConcurrentHashMap, is ConcurrentHashMap thread safe, and how does ConcurrentHashMap ensure thread safety?

HashMap is not thread-safe, ConcurrentHashMap is thread-safe, HashMap maintains an Entry array, while ConcurrentHashMap has a Segment segment, which divides the large HashMap into several segments (small HashMap), and then lets the data Hash on each segment, so that multiple threads on different segments of the Hash operation must be thread-safe, so only need to synchronize the threads on the same segment on it, thus achieving the separation of locks, greatly increasing the amount of concurrency. The invariant patterns final and volatile are also used in the implementation of ConcurrentHashMap to ensure thread safety.

4. What operations have been done by the put method of HashMap

He will recalculate the hash value according to the hashcode of key, and get the position of the element in the data according to the hash value. If the array already has other elements in that position, then the elements in this position will be stored in the form of a linked list, the newly added elements will be placed at the head of the chain, and the first to be added at the end of the chain.

Fifth, the shortcomings of HashMap

HashMap does not support concurrent operations, so it is not suitable for multithreaded environments. In a high concurrency state, if simultaneous put operations are generated and the capacity is expanded during put, a link may be formed. If the hashcode value of get key is just in the position of the link, and the corresponding value of this key is null or does not exist, it will enter an endless loop and deplete cpu memory.

VI. ConcurrentHashMap

The bottom layer is the array + red-black tree + linked list implementation, which can replace HashTable, because multiple locks are used instead of a single lock in hashTable, that is, lock separation technology. HashTable locks the entire array, which leads to low efficiency and belongs to thread safety.

The working principle of Springmvc

The user sends the request to the front-end controller DispatcherServlet,DispatcherServlet, receives the request, invokes the handlerMapping processor mapper, parses the corresponding handler of the request, starts the handlerAdapter adapter to process the request, processes the corresponding business logic and returns a ModelAndView object, selects a suitable view parser according to the returned modelAndView and returns it to DispatcherServlet, and the view parser renders the page according to view and model.

8. The parent class of the set and the difference of each subclass

Collection

├ List allows repeating values and ordered containers, maintaining the insertion order of each element

│├ LinkedList thread is not safe to add, delete and modify fast, based on linked list data structure

│├ ArrayList thread unsafe query speed is fast, based on dynamic array structure

│└ Vector thread safety

│└ Stack

├ set does not allow duplicate values and unordered containers, and cannot guarantee the storage order of elements. You can maintain a sort order through comparator or comparable of TreeSet.

│├ HashSet thread is unsafe and out of order (the order of storing and fetching is different) is not repeated, there is no index, and the underlying hash table structure query deletes quickly, increases and changes slowly.

│├ TreeSet is the only implementation of the sortedSet interface, which can be sorted

IX. What is thread safety and unsafety

Thread safety is that when multiple threads access, the locking mechanism is adopted. When one thread accesses a certain data of this class, it is protected, and other threads cannot access it until the thread has finished reading it. There will be no data inconsistency or data contamination.

Thread unsafe means that it does not provide data access protection, and it is possible to change the data after multiple threads and cause dirty data when the data is obtained.

Why do you use reids and what do you do with redis

Redis is an open source key- value database, running in memory, fast, while supporting persistence, supporting rich data structures (String,list,set,sorted set,hash), supporting subscription and publishing functions.

String: (common command get,set,incr,decr,mget) regular key-value caching applications. Count the number of visits and follow the number of people.

Hash (commonly used command hget,hset,hgetall) provinces, cities and autonomous regions linkage, user information

List (common command Ipush,rpush,Ipop) user watch list

Set registered user name cannot be duplicated. Use set record to register user.

11. How to optimize Jvm

VisualVM:jdk comes with powerful functions.

Heap information view: observe memory release, collection class check, object tree-(view heap space allocation [younger generation, older generation, persistent generation allocation], provide instant garbage collection feature, garbage monitoring), it can solve whether the size division of the older generation and the younger generation is reasonable, memory leakage, garbage collection algorithm setting is reasonable.

Thread monitoring: you can check the number of threads in the system, what state each thread is in, and deadlock check

Hotspot analysis: cpu hotspots-check which aspects of the system take up a lot of cpu time, memory hotspots-check which objects have the largest number of objects in the system.

Memory leak check: under the wrong use, the used resources can not be recycled, causing a system error. It often shows that the space of the older generation is occupied (java heap space). Generally, according to the comparison before and after garbage collection, and according to the analysis of object reference, we can basically find the leak point.

Persistent generations are tainted: exceptions thrown when storage space cannot be allocated for a new class, and the use of a large number of reflections in java results in a large number of classes generated by dynamic reflection being constantly loaded. Solution:-XX:MaxPermSize=16m

Stack overflow: usually caused by recursive non-return or circular call

Thread pool stack is full: the size of a thread in java is limited, and the value is 1m after jdk5. Solution: increasing thread stack size,-Xss2m

12. GC garbage collection mechanism

When: when the eden is full of minor gc, the object that rises to the old age is larger than the remaining space full gc of the old age, or when it is less than it is forced to full gc by the HandlePromotionFailure parameter

For what: objects that cannot be searched from root and are still not resurrected after cleaning up after the first mark.

What to do: delete unused objects and free up memory space.

Algorithm:

1. Mark-clear: it is divided into two stages: marking and clearing. First, all the objects that need to be recycled are marked, and all the marked objects are recycled uniformly after the marking is completed.

2, replication algorithm: it divides the available memory into two pieces, using only one piece at a time. When this piece of memory is used up, the surviving objects are copied to the other block, and then the used memory space is cleaned up at once.

3. Mark-collation algorithm: all living objects are moved to one end, and then the memory outside the boundary is cleared directly.

Thirteen, JVM how to GC, the new generation, the old era, persistent generation, what things are stored?

JVM uses accessibility (accessibility) analysis algorithm to mark which objects are garbage objects, and then reclaims the garbage objects. In the new generation, it uses the replication algorithm, and in the old era, it uses the tag cleaning or tag compression algorithm.

The new generation stores objects from the new new, the old ones store large objects and old objects that still exist after multiple GC, persistent generations store class information, constants (the String constant pool in JDK7 is moved to the heap), static variables (JDK7 is moved to the Java heap), class methods

The difference between strong reference, soft reference, weak reference and virtual reference

Strong reference: it is the most difficult to be recycled by GC. It is better for the virtual machine to throw an exception and interrupt the program than to recycle the object. (Object o=new Object ())

Soft reference: optional reference, reclaimed before memory overflow. The main users of soft references implement the function similar to caching. When there is enough memory, the value is obtained directly through soft references without the need to query data from busy real sources to improve speed. When memory is insufficient, this part of cached data is automatically deleted and queried from real sources.

Weak reference: reclaimed on the second garbage collection. Weak references are mainly used to monitor whether the object has been marked as garbage to be collected by the garbage collector. You can return whether the object is marked by the garbage collector through the isEnQueued method of the weak reference.

Virtual reference: it is collected during garbage collection, and the object value cannot be obtained by reference. Virtual references are mainly used to detect whether objects have been deleted from memory.

15. The principle of Spring

The internal core is ioc, dynamic injection, so that the creation of an object can be generated automatically without new, which actually makes use of the reflection in java, which is to dynamically create and call objects at run time, and spring is to dynamically create objects and call object methods with the configuration file of xml spring at run time.

Another core of Spring is the aspect-oriented programming of AOP, which can supervise and control a certain class of objects to achieve the function of heap a module expansion. This is achieved through the configuration class.

16. How to realize Aop

Static proxy: created by a programmer or automatically generated by a specific tool, and then compiled. The agent class .class file already exists when the program is running

Dynamic agent: when the program is running, it is dynamically created by using the launch mechanism.

Cglib dynamic proxy: a proxy for class implementation. Its principle is to generate a subclass for the specified target class and override the method enhancements in it, but because inheritance is used, you cannot proxy final-modified classes.

JDK's dynamic proxy relies on interfaces, and if some classes don't implement interfaces, you can't use jdk proxies, so use cglib proxies.

XVII. How to optimize MySQL

Optimize queries using query caching. (for example, NOW (), RAND () or other SQL functions do not open query caching, because returns are volatile, so all you need is a variable to replace mysql's function to open caching.)

Use the EXPLANIN keyword to detect queries (to let us know how MYSQL handles SQL statements, to help analyze query statements or table structure performance bottlenecks; how index primary keys are utilized, how data tables are searched or sorted, statement format: EXPLAIN+SELECT statements)

Use LIMIT 1 when there is only one row of data (to increase performance, stop searching after the first piece of data is found)

Index the search field (normal index INDEX: applicable to general properties such as name, email, etc., unique index UNIQUE: requires that the value of the index field is unique in the table, and the unique index allows null values. Applicable to ID card numbers, user accounts, etc., full-text index: applicable to VARCHAR and TEXT type fields)

Use a considerable type of column in the jion table and index it (when there are many jion queries, make sure that the jion fields in both tables are indexed, so that mysql will start the sql statement mechanism that optimizes JION)

Avoid using *

Always set an ID primary key for each table

Do not assign NULL as much as possible (it takes up storage space, program judgment is more complex, indexes do not store null values, use not null constraints and default values.)

Fixed-length tables are faster (easy to calculate the offset of the next data, easy to be cached and rebuilt.)

Vertical splitting: a method of turning tables in a database into several tables by column, which reduces the complexity of the table and the number of fields

Split large OR (these two large operations lock the table so that other operations cannot be entered, and you can use LIMIT to control the number of operation records)

Thank you for reading this article carefully. I hope the article "what are the P6 Java interview questions shared by the editor will be helpful to everyone?" at the same time, I also hope that you will support and pay attention to the industry information channel, and more related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report