From ant financial services internal Java interview treasure outflow unexpectedly! [collected]

osc_dc6pbw3x 2020-11-10 10:51:56
ant financial services internal java


Catalog

Preface

 MyBatis Series interview tips

1.MyBatis What is it? ?

2.Mybatis Advantages and disadvantages :

3.MyBatis and Hibernate The applicable scenarios of ?

4.MyBatis What is the functional architecture of

5.Mybatis How to perform batch operations

JVM Series interview tips

1. Detailed explanation JVM Memory model

2. Talk about the memory barrier

3.happen-before principle

4. How to break the parental delegation model ?

5. Strong citation 、 Soft citation 、 Weak reference 、 The difference between virtual references ?

 Zookeeper Series interview tips

1.Zookeeper Of java What does the client have ?

2. Say a few zookeeper Common commands .

3.Zookeeper Typical application scenarios

4. Load balancing

5. Does the cluster support dynamic addition of machines ?

6.Zookeeper Next Server Working state

 


Preface

From the ant financial services internal interview treasure flows out unexpectedly !

Interview content (JVM+Mybatis+Zookeeper), Answer attached + analysis

 MyBatis Series interview tips

1.MyBatis What is it? ?

  • Mybatis It's one and a half ORM( Object relation mapping ) frame , It encapsulates JDBC, You only need to pay attention to SQL Statement itself , It doesn't take a lot of effort to process the load driver 、 Create connection 、 establish statement And so on . Programmers write the original ecology directly sql, Can be strictly controlled sql Executive performance , High flexibility .
  • MyBatis have access to XML Or annotations to configure and map native information , take POJO Maps to records in the database , Almost all of them were avoided JDBC Code and manually set the parameters and get the result set .

2.Mybatis Advantages and disadvantages :

advantage

  • Compared with the traditional database access technology ,ORM It has the following advantages : be based on SQL Statement programming , Fairly flexible , No impact on the existing design of the application or database ,SQL Written in XML in , relieve sql Coupling with program code , Convenient for unified management ; Provide XML label , Support writing dynamics SQL sentence , And reusable .
  • And JDBC comparison , Less 50% Code quantity above , Eliminated JDBC A lot of redundant code , No need for manual switch connection .
  • Good compatibility with various databases ( because MyBatis Use JDBC To connect to the database , So as long as JDBC Supported databases MyBatis All support ).
  • Provide mapping label , Support object and database ORM Field relation mapping ; Provide object relation mapping labels , Support object relationship component maintenance .
  • Can and Spring Good integration

shortcoming

SQL Statement writing is heavy , Especially when there are many fields 、 Association table multi time , Write to developers SQL There are certain requirements for the power of sentences .

3.MyBatis and Hibernate The applicable scenarios of ?

  • MyBatis Focus on SQL In itself , Is a flexible enough DAO Layer solution .
  • The demand for performance is very high , Or projects with more changes in demand , Like the Internet Project ,MyBatis It would be a good choice .

Development difficulty and learning cost

  • Hibernate It's a heavyweight framework , High learning threshold , Suitable for relatively stable demand , Small and medium-sized projects , such as : Office automation system
  • MyBatis It's a lightweight framework , Low learning threshold , Suitable for frequent changes in demand , Large projects , such as : Internet e-commerce system

summary

  • MyBatis It's a compact 、 convenient 、 Efficient 、 Simple 、 direct 、 Semi automated persistence framework ,
  • Hibernate Is a powerful 、 convenient 、 Efficient 、 complex 、 indirect 、 Fully automated persistence framework

4.MyBatis What is the functional architecture of

 

  • We put Mybatis The functional architecture of is divided into three layers :
  • API The interface layer : Interface provided for external use API, Developers through these local API To manipulate the database . As soon as the interface layer receives the call request, it will call the data processing layer to complete the specific data processing .
  • Data processing layer : Be responsible for specific SQL lookup 、SQL analysis 、SQL Execute and execute result mapping processing, etc . Its main purpose is to complete a database operation according to the call request .
  • Foundation support layer : Responsible for the most basic functional support , Including connection management 、 Business management 、 Configure load and cache handling , These are all common things , Extract them as the most basic components . For the upper layer of data processing layer to provide the most basic support

5.Mybatis How to perform batch operations

  • Use foreach label
  • foreach Is mainly used to build in In the condition , It can be SQL Iterate over a set of statements .foreach The main attributes of a label are item,index,collection,open,separator,close.
  • item Represents the alias of each element in the collection when it iterates , Random variable names ;
  • index Specify a name , Used to represent during iteration , The position of each iteration , Not commonly used ;
  • open Indicates what the statement begins with , Commonly used “(”;
  • separator Indicates what symbol is used as a separator between each iteration , Commonly used “,”;
  • close To end with , Commonly used “)”.
  • In the use of foreach The most critical and error prone thing is collection attribute , This attribute must be specified , But in different cases , The value of this property is different , Mainly for a moment 3 In this case :

1. If a single parameter is passed in and the parameter type is one List When ,collection The property value is list

2. If a single parameter is passed in and the parameter type is one array When you have an array ,collection The property value of is array

3. If more than one parameter is passed in , We need to encapsulate them into a Map 了 , Of course, a single parameter can also be sealed

Pretend to be map, In fact, if you pass in parameters , stay MyBatis It will also be packaged into a Map Of ,map Of key Is the parameter name , So at this point collection Property values are passed in List or array Objects in their own encapsulation map Inside key.

The usage is as follows :

</select><!-- Save in bulk (foreach There are two ways to insert multiple pieces of data )
int addEmpsBatch(@Param("emps") List<Employee> emps); -->
<!-- MySQL Save in bulk , Sure foreach Traverse mysql Support values(),(),() grammar --> // Recommended
<insert id="addEmpsBatch">
INSERT INTO emp(ename,gender,email,did)
VALUES
<foreach collection="emps" item="emp" separator=",">
(#{emp.eName},#{emp.gender},#{emp.email},#{emp.dept.id})
</foreach>
</insert>
<!-- This method requires database connection properties allowMutiQueries=true Support for
Such as jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true -->
<insert id="addEmpsBatch">
<foreach collection="emps" item="emp" separator=";">
INSERT INTO emp(ename,gender,email,did)
VALUES(#{emp.eName},#{emp.gender},#{emp.email},#{emp.dept.id})
</foreach>
</insert>

Use ExecutorType.BATCH

  • Mybatis Built in ExecutorType Yes 3 Kind of , The default is simple, In this mode, it creates a new preprocessing statement for the execution of each statement , Single submission sql; and batch Patterns reuse statements that have been preprocessed , And execute all update statements in batch , obviously batch Performance will be better ; but batch Patterns have their own problems , For example Insert In operation , Before the transaction is committed , There is no way to get self increasing id, This is not in line with business requirements in certain situations
  • The usage is as follows :
// Batch storage method test 
// Batch storage method test 
@Test
public void testBatch() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
// Can perform batch operations sqlSession
SqlSession openSession =
sqlSessionFactory.openSession(ExecutorType.BATCH);
// Batch save time before execution 
long start = System.currentTimeMillis();
try {
EmployeeMapper mapper =
openSession.getMapper(EmployeeMapper.class);
for (int i = 0; i < 1000; i++) {
mapper.addEmp(new
Employee(UUID.randomUUID().toString().substring(0, 5), "b", "1"));
}
openSession.commit();
long end = System.currentTimeMillis();
// Time after batch save 
System.out.println(" The execution time " + (end - start));
// Batch precompile sql once ==》 Set parameters ==》10000 Time ==》 perform 1 Time 677
// Non batch ( precompile = Set parameters = perform )==》10000 Time 1121
} finally {
openSession.close();
}
}
  • mapper and mapper.xml as follows
public interface EmployeeMapper {
// Save employees in bulk 
Long addEmp(Employee employee);
}
```
<mapper namespace="com.jourwon.mapper.EmployeeMapper"
<!-- Save employees in bulk -->
<insert id="addEmp">
insert into employee(lastName,email,gender)
values(#{lastName},#{email},#{gender})
</insert>
</mapper>
```

The above interview questions have been filed , If you need anything, you can Click to enter Check claim information .

JVM Series interview tips

 

1. Detailed explanation JVM Memory model

Ideas : Draw the interviewer JVM Memory model diagram , And describe the definition of each module , effect , And possible problems , Such as stack overflow .

My answer :

JVM Memory structure

 

  • Program counter : The line number indicator of bytecode executed by the current thread , Used to record the address of the executing virtual machine byte instruction , Thread private .
  • Java The virtual stack : Store basic data types 、 References to objects 、 Method export, etc , Thread private .
  • Native Method stack : Similar to virtual stack , It just serves Native Method , Thread private .
  • Java Pile up :java The largest piece of memory , All object instances 、 The arrays are stored in java Pile up ,GC A place to recycle , Thread sharing .
  • Method area : Store the loaded class information 、 Constant 、 Static variables 、 Real time compiler compiled code data, etc .( Permanent belt ), The recovery target is mainly to recover the constant pool and unload the type , All threads share

2. Talk about the memory barrier

Memory barrier , Also called memory fence , It's a kind of CPU Instructions , Used to control reordering and memory visibility issues under certain conditions .

LoadLoad barrier : For statements like this Load1; LoadLoad; Load2, stay Load2 And the subsequent read operation to read the data before access , Guarantee Load1 The data to be read is read .

StoreStore barrier : For statements like this Store1; StoreStore; Store2, stay Store2 And subsequent write operations before execution , Guarantee Store1 Is visible to other processors .

LoadStore barrier : For statements like this Load1; LoadStore; Store2, stay Store2 And subsequent write operations before being brushed out , Guarantee Load1 The data to be read is read .

StoreLoad barrier : For statements like this Store1; StoreLoad; Load2, stay Load2 And all subsequent read operations before execution , Guarantee Store1 Is visible to all processors . Its overhead is the largest of the four barriers . In most processor implementations , This barrier is a universal barrier , It also functions as three other memory barriers .

3.happen-before principle

  • Single thread happen-before principle : In the same thread , The operation of writing in front of happen-before Later operations . The lock happen-before principle : The same lock unlock operation happen-before Of this lock lock operation .
  • volatile Of happen-before principle : To a volatile Variable write operation happen-before Any operation on this variable ( Of course, it also includes writing operations ).
  • happen-before The principle of transitivity : If A operation happen-before B operation ,B operation happen-before C operation , that A operation happen-before C operation .
  • Thread started happen-before principle : Of the same thread start Method happen-before Other methods of this thread .
  • Thread interrupted happen-before principle  : For threads interrupt Method call happen-before Code sent by interrupt thread detected interrupt .
  • Thread terminated happen-before principle :  All operations in the thread happen-before Thread termination detection .
  • Object created happen-before principle :  The initialization of an object is completed before its completion fifinalize Method call .

4. How to break the parental delegation model ?

Breaking the parental delegation mechanism is not just Inheritance ClassLoader class , still more rewrite loadClass and fifindClass Method .

5. Strong citation 、 Soft citation 、 Weak reference 、 The difference between virtual references ?

Ideas : Let's start with four definitions of citations , Let's talk about it with the code , It can also be extended to ThreadLocalMap The use of weak quotation in .

My answer :

1) Strong citation

We usually new An object is a strong reference , for example Object obj = new Object(); Even when there's not enough memory ,JVM

Would rather throw OutOfMemory Errors also don't recycle such objects .

2) Soft citation

If an object has only soft references , Then enough memory space , The garbage collector won't recycle it ; If there's not enough memory , It will reclaim the memory of these objects .

SoftReference<String> softRef=new SoftReference<String>(str); // Soft citation 

use :  Soft reference has important application in practice , For example, the browser's back button . When you press back , Is the content of the webpage displayed in the back page re requested or removed from the cache ? It depends on the specific implementation strategy .

(1) If a web page is recycled at the end of browsing , When you press back to view the previously viewed page , Need to rebuild

(2) If the browsing web pages are stored in memory, it will cause a lot of memory waste , It can even cause a memory overflow

The following code :

Browser prev = new Browser(); // Get the page to browse 
SoftReference sr = new SoftReference(prev); // After browsing, set it to soft reference 
if(sr.get()!=null){
rev = (Browser) sr.get(); // Has not been recycled by the recycler , Direct access to 
}else{
prev = new Browser(); // Because the memory is tight , So the object of soft reference is recycled 
sr = new SoftReference(prev); // Rebuild 
}

3) Weak reference

Objects with weak references have a shorter life cycle . In the process of the garbage collector thread scanning the memory area it governs , Once you find an object with only weak references , Whether the current memory space is enough or not , Will reclaim its memory .

String str=new String("abc");
WeakReference<String> abcWeakRef = new WeakReference<String>(str);
str=null;
Equivalent to
str = null;
System.gc();

4) Virtual reference

If an object only holds virtual references , Then it's the same as without any reference , It can be collected by the garbage collector at any time . Virtual references are mainly used to track the activities of objects recycled by the garbage collector .

 Zookeeper Series interview tips

1.Zookeeper Of java What does the client have ?

java client :zk Self contained zkclient And Apache Open source Curator.

2. Say a few zookeeper Common commands .

Common commands :ls get set create delete etc. .

3.Zookeeper Typical application scenarios

Zookeeper It's a typical release / The distributed data management and coordination framework of subscription mode , Developers can use it to publish and subscribe distributed data .

Through to Zookeeper The rich data nodes in are used in cross , coordination Watcher Event notification mechanism , It is very convenient to build a series of core functions that will be involved in distributed applications , Such as :

(1) Data Publishing / subscribe

(2) Load balancing

(3) Naming service

(4) Distributed coordination / notice

(5) Cluster management (6)Master The election

(7) Distributed lock

(8) Distributed queues

4. Load balancing

zk The naming service

Naming service is to obtain the address of a resource or service by a specified name , utilize zk Create a global path , This path can be used as a name , Point to the cluster in the cluster , Address of the service provided , Or a remote object and so on .

5. Does the cluster support dynamic addition of machines ?

In fact, it is the horizontal expansion ,Zookeeper Not so good in this respect . Two ways :

Restart all : Close all Zookeeper service , Change the configuration and start . Does not affect previous client sessions .

Restart one by one : Under the principle that more than half of life is available , The restart of a machine does not affect the external service provided by the whole cluster . This is a common way .

3.5 The version starts to support dynamic expansion

6.Zookeeper Next Server Working state

The server has four states , Namely LOOKING、FOLLOWING、LEADING、OBSERVING.

(1)LOOKING: Look for look for Leader state . When the server is in this state , It will assume that there is no Leader, So we need to enter Leader Election status .

(2)FOLLOWING: Follower status . Indicates that the current server role is Follower.

(3)LEADING: Leadership status . Indicates that the current server role is Leader.

(4)OBSERVING: Observer status . Indicates that the current server role is Observer.

7.Chroot characteristic

3.2.0 After version , Added Chroot characteristic , This feature allows each client to set a namespace for itself . If a client is set up Chroot, Then any operation of the client to the server , Will be limited to its own namespace .

By setting Chroot, Be able to apply a client to Zookeeper A subtree on the server side corresponds to , In those multiple applications, there is one Zookeeper In the group scene , It is very helpful to realize the isolation between different applications .

Finally, the welfare from Xiaobian

 

The following interview questions and answers are a collection compiled by a small editor for a long time , The partner who needs to get it can   Am I Free collection  , I wish the students who want to go to the factory for an interview , win victory the moment one raises one 's standard ,offer Get a hand cramp .

Some data and pictures :

 

版权声明
本文为[osc_dc6pbw3x]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云