Home  >  Article  >  Java  >  A collection of Java interview questions - Recommended interview questions to help you get the offer easily

A collection of Java interview questions - Recommended interview questions to help you get the offer easily

php是最好的语言
php是最好的语言Original
2018-08-02 10:54:372244browse

Preface

Only a bald head can become strong

When I was blogging before, I found that some well-written blogs would be collected silently. I've been checking up on omissions recently, and some knowledge points are relatively important, but I haven't written them in my previous blog, so I took advantage of my free time to sort them out (recommended: JAVA Interview Questions Collection).

Knowledge points of the text:

  • Integer constant pool

  • TCP unpacking and sticking

  • select, poll, epollSimple difference

  • Synchronize lock optimization after jdk1.6

  • Java memory model

This article strives to briefly explain each knowledge point, I hope everyone will gain something after reading it

1. The magical Integer

I saw someone discussing the true or false issue of Integer in a group a while ago. I thought I already understood this knowledge point. But I still made a mistake, so I asked a friend for advice. A friend sent me another picture:

A collection of Java interview questions - Recommended interview questions to help you get the offer easily

Later I found out that this is from "In-depth Understanding of Java Virtual Machine - JVM Advanced Features and Best Practices (2nd Edition)" )》In section 10.3.2~

public class Main_1 {
    public static void main(String[] args) {
        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        Long h = 2L;
        System.out.println(c == d);
        System.out.println(e == f);
        System.out.println(c == (a + b));
        System.out.println(c.equals(a + b));
        System.out.println(g == (a + b));
        System.out.println(g.equals(a + b));
        System.out.println(g.equals(a + h));
    }

}

you can think about it first and then read down the answers to see if you can get it right.

1.1 Problem-solving ideas

Before solving this problem, I believe many people already know that there is an Integer cache pool in Java, and the cache size is: - 128~127

A collection of Java interview questions - Recommended interview questions to help you get the offer easilyThe answer is:

  • true

  • false

  • true

  • true

  • true

  • false

  • true

A brief explanation:

  • Use ==:

    • If you compare Integer variables, the address value is compared by default.

    • Java's Integer maintains a cache pool from -128~127

    • If there is an operation on one side of the comparison expression (such as a b), then the comparison is the specific numerical value

  • ##Using

    equals():

    • Whether it is Integer or Long,

      equals()default comparison is numeric value.

    • Long's

      equals() method, the default implementation of JDK: will determine whether it is a Long type

  • Pay attention to automatic unboxing and automatic packing issues.

A collection of Java interview questions - Recommended interview questions to help you get the offer easily

Decompile and see:

import java.io.PrintStream;

public class Main_1 {
    public static void main(String[] paramArrayOfString) {
        Integer localInteger1 = Integer.valueOf(1);
        Integer localInteger2 = Integer.valueOf(2);
        Integer localInteger3 = Integer.valueOf(3);
        Integer localInteger4 = Integer.valueOf(3);
        Integer localInteger5 = Integer.valueOf(321);
        Integer localInteger6 = Integer.valueOf(321);
        Long localLong = Long.valueOf(3L);

        // 缓存池
        System.out.println(localInteger3 == localInteger4);
        
        // 超出缓存池范围
        System.out.println(localInteger5 == localInteger6);
        
        // 存在a+b数值表达式,比较的是数值
        System.out.println(localInteger3.intValue() == localInteger1.intValue() + localInteger2.intValue());

        // equals比较的是数值
        System.out.println(localInteger3.equals(Integer.valueOf(localInteger1.intValue() + localInteger2.intValue())));
        // 存在a+b数值表达式,比较的是数值
        System.out.println(localLong.longValue() == localInteger1.intValue() + localInteger2.intValue());
        // Long的equals()先判断传递进来的是不是Long类型,而a+b自动装箱的是Integer类型
        System.out.println(localLong.equals(Integer.valueOf(localInteger1.intValue() + localInteger2.intValue())));

        // ... 最后一句在这里漏掉了,大家应该可以推断出来
    }
}

The decompilation tool I use is

jd-gui , if you haven’t tried decompilation yet, you can download it and play with it:

  • https://github.com/java-decompiler/jd-gui/releases

2. What are the Synchronize lock optimization methods?

Multi-threaded article review:

  • ThreadLocal is so simple

  • You can get started with multi-threading in three minutes!

  • Thread source code analysis

  • Multi-threading basics and necessary knowledge points! Read Learn Multithreading and Get twice the result with half the effort

  • Java lock mechanism

  • AQS simply go through it

  • Lock subclass to learn about

  • Thread pool, don’t you really want to learn about it?

  • The deadlock of multi-threading is so simple

  • Three young guys who support Java multi-threading

When I wrote a multi-threading article before, I briefly mentioned that synchronized locks will have various optimizations after jdk1.6: adapting to spin locks, lock elimination, lock coarsening, lightweight locks, and biased locks.

A collection of Java interview questions - Recommended interview questions to help you get the offer easily

I thought these optimizations were very difficult to understand, but actually~~~it’s easy to understand with a brief understanding.

2.1 Adapt to spin lock

Lock competition is in kernel mode, and it will go through the

switching from user mode to kernel mode, yes It takes more time.

The reason why the spin lock appears is that people find that most of the time the lock occupation only lasts for a short time, even less than the time it takes to switch to kernel mode time, so let the thread wait for a limited time before entering kernel mode. If the lock can be acquired within this time, a lot of unnecessary time will be avoided . If not, then enter kernel mode to compete for the lock. The adaptive spin lock was introduced in JDK 1.6, indicating that

the time of spin is not fixed, and it becomes smarter to spin or not

.

自旋锁在JDK1.4.2中就已经引入,只不过默认是关闭的,可以使用-XX:+UseSpinning参数来开启,在JDK1.6中就已经改为默认开启了。

2.2锁消除

如果JVM明显检测到某段代码是线程安全的(言外之意:无锁也是安全的),JVM会安全地原有的锁消除掉!

比如说:

    public void vectorTest(){
        Vector<String> vector = new Vector<String>();
        for(int i = 0 ; i < 10 ; i++){
            vector.add(i + "");
        }

        System.out.println(vector);
    }

Vector是默认加锁的,但JVM如果发现vector变量仅仅在vectorTest()方法中使用,那该vector是线程安全的。JVM会把vector内部加的锁去除,这个优化就叫做:锁消除。

2.3锁粗化

默认情况下,总是推荐将同步块的作用范围限制得尽量小

但是如果一系列的连续操作都对同一个对象反复加锁和解锁,甚至加锁操作是出现在循环体中的,频繁地进行互斥同步操作也会导致不必要的性能损耗

JVM会将加锁的范围扩展(粗化),这就叫做锁粗化。

2.4轻量级锁

轻量级锁能提升程序同步性能的依据是“对于绝大部分的锁,在整个同步周期内都是不存在竞争的”,这是一个经验数据。

  • 如果没有竞争,轻量级锁使用CAS操作避免了使用互斥量的开销

  • 但如果存在锁竞争,除了互斥量的开销外,还额外发生了CAS操作,因此在有竞争的情况下,轻量级锁会比传统的重量级锁更慢。

简单来说:如果发现同步周期内都是不存在竞争,JVM会使用CAS操作来替代操作系统互斥量。这个优化就被叫做轻量级锁。

2.5偏向锁

偏向锁就是在无竞争的情况下把整个同步都消除掉,连CAS操作都不做了

偏向锁可以提高带有同步但无竞争的程序性能。它同样是一个带有效益权衡(Trade Off)性质的优化,也就是说,它并不一定总是对程序运行有利,如果程序中大多数的锁总是被多个不同的线程访问,那偏向模式就是多余的。在具体问题具体分析的前提下,有时候使用参数-XX:-UseBiasedLocking来禁止偏向锁优化反而可以提升性能。

2.6简单总结各种锁优化

  • 自适应偏向锁:自旋时间不固定

  • 锁消除:如果发现代码是线程安全的,将锁去掉

  • 锁粗化:加锁范围过小(重复加锁),将加锁的范围扩展

  • 轻量级锁:在无竞争的情况下使用CAS操作去消除同步使用的互斥量

  • 偏向锁:在无竞争环境下,把整个同步都消除,CAS也不做。

参考资料:

  • https://blog.csdn.net/chenssy/article/details/54883355

三、TCP粘包,拆包

这是在看wangjingxin大佬面经的时候看到的面试题,之前对TCP粘包,拆包没什么概念,于是就简单去了解一下。

3.1什么是拆包粘包?为什么会出现?

在进行Java NIO学习时,可能会发现:如果客户端连续不断的向服务端发送数据包时,服务端接收的数据会出现两个数据包粘在一起的情况。

TCP的首部格式:

A collection of Java interview questions - Recommended interview questions to help you get the offer easily

  • TCP是基于字节流的,虽然应用层和TCP传输层之间的数据交互是大小不等的数据块,但是TCP把这些数据块仅仅看成一连串无结构的字节流,没有边界

  • 从TCP的帧结构也可以看出,在TCP的首部没有表示数据长度的字段

基于上面两点,在使用TCP传输数据时,才有粘包或者拆包现象发生的可能。

一个数据包中包含了发送端发送的两个数据包的信息,这种现象即为粘包

A collection of Java interview questions - Recommended interview questions to help you get the offer easily

接收端收到了两个数据包,但是这两个数据包要么是不完整的,要么就是多出来一块,这种情况即发生了拆包和粘包

A collection of Java interview questions - Recommended interview questions to help you get the offer easily

拆包和粘包的问题导致接收端在处理的时候会非常困难(因为无法区分一个完整的数据包)

3.2 Solving unpacking and sticking

The subpackaging mechanism generally has two general solutions:

  • 1, special characters Control

  • 2, add the length of the data packet in the header capital

If you use netty, there are special encoders and decoders to solve it Problems with unpacking and gluing packages.

tips:UDP does not have packet sticking problem, but there is packet loss and disorder. There will be no incomplete packages, and all packages received will be completely correct. The data unit protocol transmitted is UDP message or user datagram, which is neither merged nor split when sent.

4. Simple differences between select, poll, and epoll

NIO review:

  • JDK10 has been released, how much do you know about nio?

This is how it implements the I/O reuse model under Linux:

Call one of the select/poll/epoll functions, Pass in multiple file descriptors and return if one is ready, otherwise block until timeout.

There are some differences between these functions. Some interviewers may ask what are the differences between these three functions:

The differences are as follows:

A collection of Java interview questions - Recommended interview questions to help you get the offer easily

Two sentence summary:

  • ## Both select and poll need to poll each file descriptor, epoll Based on event-driven, there is no need to poll

  • ##select and poll

    need to copy the file descriptor every time, epoll is not required

  • select

    The maximum number of connections is limited, epoll and pollThe maximum number of connections is not limited

  • tips:epoll Implementation in the kernel, using red-black tree to manage event blocks
4.1 Popular example

Now 3y is interning in the company, and the code he has written needs to be tested.

select/poll

Situation:

    Development is writing code, testing at this time
  • Ask all developers one by one, you Have you written the program? Want to test?

  • epoll
Situation:

After the developer has finished writing the code, tell the test: "I have written the code, you Go and test it, the function is XXX". So the tester happily looked for bugs.
  • Other popular descriptions[1]:
A bartender (a thread), with a group of drunks lying in front of him, suddenly shouted "Pour the wine" (incident ), you trot over to pour him a drink, and then let him go. Suddenly another one wants to pour a drink, and you go over and pour it again. Just like this, one waiter serves many people. Sometimes no one drinks, and the waiter is idle and can do some work. Otherwise, play with your mobile phone. As for epoll and select, the difference between poll and poll is that the drunken people in the latter two scenes do not speak. You have to ask one by one if you want a drink, and you have no time to play with your mobile phone. io multiplexing probably means these drunkards share a waiter.

Other popular descriptions[2]:
A simple example (maybe not very vivid) select/pollThe hotel waiter (kernel) tells the hotel owner (user program): "There are guests now. Checkout: "But no one of the waiters clearly told the boss which tables the guests were paying for. The boss has to go to each table and ask: Do you want to pay? The epoll hotel waiter (kernel) tells the hotel owner (user program): "Guests No. 1, 2, and 5 check out." The boss can go directly to tables 1, 2, and 5 to collect money

5. Java memory model
JVM blog post review:

How did JVM go from getting started to giving up?
  • When I was writing JVM before, I once confused the
  • JVM memory structure and the Java memory model
~~~Fortunately, some enthusiastic netizens gave me some help point out.

JVM memory structure:

Java memory model: A collection of Java interview questions - Recommended interview questions to help you get the offer easily

Rules when operating variables: A collection of Java interview questions - Recommended interview questions to help you get the offer easily

The Java memory model stipulates that all
    variables are stored in the main memory
  • working memory of the thread
  • The main memory of the variables used by the thread is saved

    Copy copy

    All
  • operations of the thread on variables
  • (read Fetching, assigning, etc.) must be done

    in the working memory, and variables in the main memory cannot be directly read and written

    Synchronize back to the main memory from the
  • working memory Memory
is implemented through the following 8 operations:

lock (lock): Acts on variables in main memory, marking a variable as exclusive to one thread.
  • unlock (unlock): Acts on main memory variables to release a variable that is in a locked state. Only the released variable can be locked by other threads.
  • read (read): Acts on the main memory variable, transferring a variable value from the main memory to the working memory of the thread, so that it can be used by the subsequent load action

  • Load: Acts on variables in working memory. It puts the variable value obtained from main memory by the read operation into a copy of the variable in working memory.

  • use (use): Acts on a variable in the working memory, passing a variable value in the working memory to the execution engine. Whenever the virtual machine encounters a word that needs to use the value of the variable This operation will be performed during the section code instruction.

  • assign (assignment): Acts on a variable in the working memory. It assigns a value received from the execution engine to a variable in the working memory. Whenever the virtual machine encounters a variable assignment This operation is performed when executing bytecode instructions.

  • store (storage): Acts on variables in working memory, transferring the value of a variable in working memory to main memory for subsequent write operations.

  • write (write): Acts on variables in main memory. It transfers the store operation from the value of a variable in working memory to a variable in main memory.

The Java memory model is built around the three characteristics of how to handle atomicity, visibility and orderliness during concurrent processes

Operations that guarantee atomicity:

  • read, load, assign, use, store and write

  • synchronized Lock

Operation to ensure orderliness (reordering leads to disorder):

  • volatile

  • synchronized lock

Guaranteed visibility:

  • volatile

  • synchronized lock

  • final

As mentioned above, orderliness can be guaranteed through volatile and synchronized locks, but when we usually write programs Don't always pay attention to the orderliness of the code. In fact, we have a principle within Java called happens-before principle(happens-before)

  • The "happens-before" principle can be passed: Several rules comprehensively solve all the problems of possible conflicts between two operations in a concurrent environment

  • With these rules, And our operations are within the scope defined by these rules. We can ensure that operation A will definitely occur before operation B (there will be no reordering problem)

The "happens-before" principle has the following:

  • Program Order Rule: Within a thread, according to the order of the program code, operations written in the front occur before operations written in the back. To be precise, it should be the control flow sequence rather than the program code sequence, because structures such as branches and loops need to be considered.

  • Monitor Lock Rule: An unlock operation occurs before a subsequent lock operation on the same lock. What must be emphasized here is the same lock, and "later" refers to the sequence in time.

  • volatile variable rule (Volatile Variable Rule): The writing operation of a volatile variable occurs first before the subsequent reading operation of this variable. The "after" here also refers to time. sequence. Thread Start Rule: The start() method of the Thread object precedes every action of this thread.

  • Thread Termination Rule: All operations in a thread occur first in the termination detection of this thread. We can end it through the Thread.join() method, Thread. The return value of isAlive() and other means detect that the thread has terminated execution.

  • Thread Interruption Rule: The call to the thread interrupt() method occurs first before the code of the interrupted thread detects the occurrence of the interrupt event. You can pass Thread.interrupted( ) method detects whether an interrupt occurs.

  • Object finalization rule (Finalizer Rule): The initialization of an object (the end of constructor execution) occurs first at the beginning of its finalize() method.

  • Transitivity: If operation A occurs before operation B, and operation B occurs before operation C, then we can conclude that operation A occurs before operation C.

Related articles:

Share a summary of interview questions in Java

10 classic Java main method interview questions

The above is the detailed content of A collection of Java interview questions - Recommended interview questions to help you get the offer easily. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn