Senior Java interview questions to collect

Java concepts title

Unpacking boxes of principle

The compiler calls when valueOf autoboxing convert an object into a primitive type, and automatically unpacking, by invoking the compiler similar intValue (), doubleValue () method of the kind of object into a primitive type.

Only double and float autoboxing code does not use the cache, each time a new object is new, the other six basic types use a caching policy.     

Use caching strategy is because cached objects that are frequently used to (such as characters, numbers between -128 to 127), to prevent automatic packing are created once every instance of an object.     

And double, float is a float, the cache is not particularly no effect of hot (frequently used) data several other types of high efficiency.

Principles of reflection, reflection to create a class instance

Capable of dynamically at run time to obtain the type of a class of information

Create a Class object class in three ways :

  • 对象.getClass()the way
  • 类名.Classthe way
  • Class.forName( 类的包名 ) the way

Reflection performance reasons slow

  • By name reflected the need to retrieve classes and methods, there is a certain time overhead.
  • Dynamic process involving reflection type, some virtual machines can not execute performance optimization.

Deep and shallow copy copy

If a copy of the object when only the basic data types are copied, but only for reference data types were passing references, but no real create a new object, believed to be shallow copy. On the contrary, when a reference copy of the data type, create a new object and copy member variables within it, then that is a deep copy.

Implement Cloneableinterface replication clone()method, it is achieved shallow copy

Spring concept title

The principle of Spring AOP and IOC

IOC:

IOC (inversion control) is a programming paradigm, the system can solve the complex problem of too high degree of coupling an object to a certain extent, not Spring patents. The most common way is to IOC DI (Dependency Injection), through a container, Bean will maintain it for future use in other places directly, rather than re-new.

Why DI can play the role of decoupling?
A software system comprising a large number of objects, each object has dependencies, during the preparation process common software object definition files distributed among various dependencies between objects, only through the class constructor parameter passing, a method parameter passing to complete the form. When the project is large, complex logic dependencies between objects will become very difficult to sort out.
In the Spring IOC in general, we can in the XML file, the dependencies between the preparation of a unified definition of bean, bean and bean, thus increasing the clarity of logic. Moreover, bean created by Spring to complete, the programmer does not need to be concerned about, programmers only need to concentrate on the business logic above, reducing the burden of thinking.

When reading the application provides Spring Bean boot configuration information and generate a corresponding Bean Spring container disposed in registry, and then according to this example of the registry Bean, assembled dependencies between Bean, for the upper application provide ready operating environment.

Bean buffer pool: HashMap achieve

Idea of ​​dependency injection is achieved through reflection, when instantiating a class that set methods in the class attribute stored beforehand Bean buffer pool (the HashMap) is injected into the class class invoked by reflection.

AOP:

The principle is actually aop java dynamic proxy, but jdk dynamic proxy must implement the interface, so the spring aop cglib this library is implemented, cglib uses frames asm this direct manipulation of bytecode, it can be done does not implement interface dynamic proxy complete in the case.

The difference between Spring and factoryBean of beanFactory

The principle underlying the Mybatis

spring the controller is a single case or multiple cases, how to ensure the safety of concurrent

The default controller is a single case, do not use non-static member variables, otherwise the data will occur logical confusion.
Because it is not a singleton thread safe.

Supplement
spring bean scope has the following five:

  • singleton: Singleton, created when the spring applicationContext container, spring will want to initialize all the scope instance, with lazy-init pretreatment avoided;

  • prototype: prototype mode, each will produce a new instance by getBean get the bean, the spring will no longer create its management;

(The following is only used in the web of the project)

Internet Conceptual Questions

TIME_WAIT state and CLOSE_WAIT difference

The three states are used: ESTABLISHED showing communicating, TIME_WAIT represents actively closed, CLOSE_WAIT represents passive close.

TCP protocol provides for the connection has been established, both the network to be disconnected four-way handshake to succeed, if the lack of one of these steps will make the connection in a state of suspended animation, the connection resources occupied by itself will not be released. The web server program to manage large number of connections, it is necessary to ensure that the connection is completely disconnected useless, or a large number of dead connections will waste a lot of server resources. Among the many TCP state, most notably the state has two: CLOSE_WAIT and TIME_WAIT.

TIME_WAIT

TIME_WAIT is formed when the active link closed, 2MSL waiting time, about 4 minutes. Mainly to prevent the loss of the last ACK. Since the TIME_WAIT time will be very long, and therefore should be minimized server-side active close connection

The CLOSE_WAIT
the CLOSE_WAIT passive close the connection formed. The TCP state machine, the server receives the client sends the FIN, the TCP implementation according to the ACK transmission, thus entering CLOSE_WAIT state. However, if the server does not perform close (), can not migrate to the CLOSE_WAIT LAST_ACK, the present system will be connected to many CLOSE_WAIT state. At this point, the system may be busy processing read and write operations, without the connection FIN has been received, and be close. At this point, recv / read connection socket FIN has been received, it will return 0.

Why TIME_WAIT state?
Assuming that the final ACK is lost, server will retransmit FIN, client must maintain state information for TCP can retransmit the final ACK, otherwise it will send a RST, consider the results of server error occurred. TCP implementations must be reliably connected to terminate both directions (full duplex off), client must enter TIME_WAIT state, as the case may face client final ACK is retransmitted.

Why 2MSL TIME_WAIT state needs to maintain such a long time?

RFC 793 [Postel 1981c] pointed out that MSL is 2 minutes. However, conventional implementations value is 30 seconds, 1 minute, or 2 minutes.

2MSL i.e. twice the MSL, the TCP TIME_WAIT state is also referred 2MSL waiting state, when the end of a TCP initiate actively closed, after sending a last ACK packet, i.e. after completion of the third handshake ACK packet transmitted fourth handshake after entering TIME_WAIT state, you must stay MSL twice the time in this state.
Waiting time 2MSL main purpose is afraid of each other last ACK packet is not received, then the other retransmission third handshake FIN packet after the timeout, take the initiative to shut down after the end to the retransmitted packets can then send a FIN ACK response packet.
Ports on both ends in the TIME_WAIT state can not be used until the end of time 2MSL to continue using.
When the connection is no waiting period 2MSL late segment will be discarded. However, in practical applications you may not have to wait 2MSL time ends before using this port by setting the option SO_REUSEADDR reach.

TIME_WAIT and * CLOSE_WAIT * status socket too

If the server is out of the abnormal, ninety eight percent are the following two cases:

1. The server maintains a large number of TIME_WAIT state

2. The server maintains a large CLOSE_WAIT state, in short, is due to the large number of CLOSE_WAIT too passive to close the connection due to improper handling.

Because linux is assigned to a user's file handle is limited, and if TIME_WAIT and CLOSE_WAIT two states have been maintained, it means that a corresponding number of channels it has been occupied, and is "profit at others hard," Once Maximum number of handles, a new request can not be dealt with, followed by a large number of abnormal Too Many Open Files, Tomcat crash.

redis Conceptual Questions

What is complicated by competition redis? how to solve this problem? Learn CAS redis affairs program do?

This line is also a very common problem is multi-client concurrent write a key, after probably should have first come to the data, leading to the wrong version of the data; or multiple clients at the same time get a key, and then modify the value after write back, as long as the order is wrong, wrong data.

Solution

  • zookeeper achieve Distributed Lock
  • You have to write cached data is found out from the mysql, mysql had to be written, the writing time mysql must be saved in a time stamp, check out the mysql time, also check out the time stamp.
  • Every time you want before you write, first determine what the current value of the timestamp is newer than the timestamp of the value of the cache. If so, you can write, otherwise, the old data can not be used to cover the new data.

Mysql Conceptual Questions

Mysql difference in the MyISAM and InnoDB

  • InnoDB supports transactions, MyISAM does not support transactions. This is one of the important reasons MySQL will become the default storage engine from MyISAM to InnoDB;

  • Support InnoDB foreign keys, and MyISAM does not support. For a table that contains InnoDB foreign keys into MYISAM fail;

  • InnoDB is a clustered index, MyISAM is a non-clustered index. Clustered index files stored in the leaf nodes of the primary key index, InnoDB therefore must have a primary key, the primary key index is very efficient. But it requires two auxiliary index query, the first query to the primary key, and then query the data by primary key. Therefore, the primary key should not be too big because the primary key is too big, the other indexes also will be great. Whereas non-aggregated MyISAM index, separate data file, the index pointer stored in the data file. Primary key index and secondary indexes are independent.

  • InnoDB specific number of rows in the table is not saved, execute select count (*) requires a full table scan from table. And MyISAM with a variable number of lines to save the whole table, only when executing the read statement to the variable, fast;

  • InnoDB minimum row locks lock granularity, the lock granularity is the minimum MyISAM table lock. An update statement will lock the entire table, leading to other queries and updates are blocked, so concurrent access is limited. This is the default storage engine MySQL will become one of the important reasons for InnoDB from MyISAM;

Policy issues

There 2000w mySQL data, only the data stored in redis 20w, how to ensure that the data is hot data in redis?

It provides a simple implementation of the idea of cache invalidation: LRU (least recently used out)
i.e. redis cache hit every time, give a certain increase in the cache hit TTL (time expired) (set according to specific circumstances, such as 10 minutes) .
after some time, the heat will ttl data is large, it does not expire automatically, substantially over the cold ttl data set immediately ineffective.

redis offers six data out of the policy:

redis memory size of the data set to rise to a certain size and they will perform data elimination strategy. redis-out policy data provides 6:
volatile-LRU: least recently used to pick out a data set from the data set the expiration time (server.db [i] .expires) in
volatile-ttl: expiration time has been set from the data set (server.db [i] .expires) were selected to be stale data out
volatile-random: arbitrarily selecting data from the set-out expiration time data set (server.db [i] .expires) in
allkeys-lru: data from set (server.db [i] .dict) were selected out of the least recently used data
allkeys-random: the data set (server.db [i] .dict) select any data out
no-enviction (expulsion): prohibits the expulsion data

Distributed unique id

  1. UUID

The core idea is to combine machine card, local time, with a record number to generate the UUID.

  • Advantages: locally generated, to generate a simple, good performance, high availability no risk
  • Disadvantages: too long, the redundant memory, and random unreadable, low search efficiency
  1. Database increment ID

Use database id increment strategies, such as MySQL's auto_increment. And may be provided using two databases are not synchronized long Unique ID is generated strategies to achieve high availability.

  • Pros: database-generated ID is absolutely orderly and simple way to achieve high availability
  • Disadvantages: the need to deploy a separate database instance, high cost, there are performance bottlenecks
  1. Batch generation ID

Generating a plurality of batches on demand ID, each build is in need access to the database, the database is modified to the maximum value of ID, and record the current value and the maximum value in memory.

  • Advantages: avoiding every generation ID to access the database and must bring pressure to improve performance
  • Cons: belonging to the local generation strategy, there is a single point of failure, caused by the restart ID service discontinuities
  1. Generation ID Redis

Redis commands all operations are single-threaded, offers itself as incr and increby such self-command adatoms, they are able to ensure the generated ID must be the only orderly.

  • Advantages: does not depend on a database, flexible and convenient, and is superior to the database; natural ordering ID number, the results need to sort tab or helpful.
  • Disadvantage: If the system does not have the Redis, need to introduce new components, increasing the complexity of the system; and the configuration need to be coded to the effort.

Considering the performance bottleneck of a single node, the cluster may be used to obtain Redis higher throughput. If a cluster has five Redis. Can initialize each of Redis values ​​are 1, 2, 3, 4, 5, and 5 are steps. Redis generated ID for the respective:

A:1, 6, 11, 16, 21
B:2, 7, 12, 17, 22
C:3, 8, 13, 18, 23
D:4, 9, 14, 19, 24
E:5, 10, 15, 20, 25
复制代码

Just load to determine which machine is good, the future is difficult to make changes. Step and an initial value necessarily be determined in advance. Use Redis clustering problem can be way single point of failure.

Further, using more suitable to generate serial Redis day starting from 0. Such as order number = Date + day since growth numbers. Key may be generated each day in a Redis using INCR accumulated.

  1. Twitter's algorithm snowflake

Twitter generates a global ID service Snowflake: github.com/twitter/sno...

Shown above, Twitter Snowflake algorithm is represented by the following components:

  • A sign bit:

Since long type in java signed the most significant bit is the sign bit, n is 0, 1 is negative, and the actual system ID used are generally positive, the most significant bit is 0.

  • 41 timestamp (in milliseconds):

It should be noted here that the timestamp 41 is not stored timestamp of the current time, but the difference between the stored timestamp (current timestamp - time stamp start), where ID is the starting time stamp generator typically begins timestamp used to specify the program, so a maximum of 41 milliseconds, the time stamp may be used (1 << 41) / (1000x60x60x24x365) = 69年.

  • 10 data bits Machine:

5 comprises a data identification bit and 5-bit machine ID, which determines the distributed system 10 can be deployed up to 1 << 10 = 1024s nodes. This number is exceeded, the generated ID is likely to be conflict.

  • 12 ms in sequence:

This support 12 of each node counts per millisecond (same machine, same time) up to generate 1 << 12 = 4096个ID

Add up to exactly 64, a Long type.

advantage:

1) does not depend on a database, flexibility, and superior performance database.

2) ID in a time on a single machine is incremented.

Disadvantages:

1) on a single machine is increasing, but as it relates to a distributed environment, the clock on each machine can not be completely synchronized, maybe sometimes is not the case there will be increasing globally.

Database generation

In MySQL example, using a field setting auto_increment_incrementand auto_increment_offsetto ensure that the self-energizing ID, each service MySQL obtained using the following SQL read ID number.

begin;
REPLACE INTO Tickets64 (stub) VALUES ('a');
SELECT LAST_INSERT_ID();
commit;

The advantages and disadvantages of this approach are as follows:

advantage:

  • Very simple, using the existing database system function realization, small cost, DBA professional maintenance.
  • ID number incremented monotonically, can achieve some special requirements for service ID.

Disadvantages:

  • Strong dependence DB, DB abnormality when the system is unavailable, is a fatal problem. From the master copy can be configured to increase the availability of possible, but difficult to ensure data consistency in exceptional circumstances. When switching from the main inconsistency may result in duplicate Fa.
  • ID numbers issued in a single performance bottleneck MySQL read and write performance.

For MySQL performance problems, solutions are available as follows: In a distributed system we can deploy more than a few machines, each machine set a different initial value and step size and an equal number of machines. For example, there are two machines. Setting step of step 2, an initial value 1 TicketServer1 (1,3,5,7,9,11 ...), initial TicketServer2 value of 2 (2,4,6,8,10 ...).

US Mission Leaf

Leaf is the beauty of open source distributed group ID generator, to ensure global uniqueness, the trend is incremented monotonically increasing, information security, which also mentioned a comparison of several distributed approach, but also need to rely on a relational database, Zookeeper middleware .

Specifically refer to the official website Description: tech.meituan.com/MT_Leaf.htm...

reference:

2019 Latest Ali interpolation Senior Java interview questions

Spring IOC principle summary

Guess you like

Origin www.cnblogs.com/hongdada/p/12037827.html