Do you know these 10 difficult Java interview questions?

王林
Release: 2020-09-19 17:11:49
forward
2748 people have browsed it

Do you know these 10 difficult Java interview questions?

This is my collection of the 10 toughest Java interview questions. These questions mainly come from the core part of Java and do not involve Java EE related issues. You may know the answers to these tough Java questions, or feel like they don’t challenge your Java knowledge enough, but these questions are easily asked in various Java interviews, and many, including my friends and colleagues Programmers find it difficult to answer.

(More interview question recommendations: java interview questions and answers)

1. Why are waits and notifications declared in the Object class instead of Thread?

A tough Java question, how can you answer this question if the Java programming language was not designed by you. General knowledge and in-depth understanding of Java programming will help answer this tough core Java interview question.

Why wait, notify and notifyAll are defined in the Object class instead of the Thread class

This is a famous Java interview question, Recruitment 2~4 You may encounter interviews with senior Java developers with years of experience.

The good thing about this question is that it reflects the interviewer's understanding of the waiting notification mechanism and whether his understanding of this topic is clear. Like the question of why multiple inheritance is not supported in Java or why String is final in Java, this question may have multiple answers.

Why wait and notify methods are defined in the Object class, everyone can tell some reasons. Judging from my interview experience, wait and nofity are still the most confusing for most Java programmers, especially developers with 2 to 3 years of experience. If they are asked to use wait and notify, they will be confused. So, if you go for a Java interview, make sure you have a good understanding of wait and notify mechanisms and can easily write code using wait and understand the mechanics of notification through producer-consumer problem or implementing blocking queue etc.

Why wait and notify need to be called from a synchronized block or method, and the differences between wait, sleep and yield methods in Java, you will find it interesting to read if you haven't already. Why wait, notify and notifyAll belong to Object class? Why shouldn't they be in Thread class? Here are some ideas that I think make sense:

1) wait and notify are not just ordinary methods or synchronization Tools, and more importantly they are the communication mechanism between two threads in Java. For language designers, if this communication mechanism cannot be implemented through Java keywords (such as synchronized), and at the same time ensure that this mechanism is available to every object, then the Object class is the correct declaration place. Remember syncing and waiting for notifications are two different areas, don't treat them as the same or related. Synchronization provides mutual exclusion and ensures thread safety of Java classes, while wait and notify are communication mechanisms between two threads.

2) Every object can be locked, which is another reason to declare wait and notify in the Object class instead of the Thread class.

3) In order to enter the critical section of the code in Java, threads need to lock and wait for the lock, they do not know which threads hold the lock, but only know that the lock is held by a certain Threads hold and they should wait to acquire the lock, rather than knowing which thread is inside the synchronized block and requesting them to release the lock.

4) Java is based on the idea of ​​Hoare's monitor. In Java, all objects have a monitor.

The thread waits on the monitor. To execute the wait, we need 2 parameters:

  • One thread

  • One Monitor (any object)

In Java design, the thread cannot be specified, it is always the thread running the current code. However, we can specify a monitor (this is what we call the wait object). This is a good design because if we could have any other thread waiting on the desired monitor, this would lead to "intrusions" that would cause difficulties when designing concurrent programs. Remember that in Java, all operations that intrude on the execution of another thread are deprecated (such as the stop method).

2. Why is multiple inheritance not supported in Java?

I find this Java core question difficult to answer because your answer may not satisfy the interviewer, in most cases the interviewer is looking for the key points in the answer and if you mention these key points point and the interviewer will be happy. The key to answering tough questions like this in Java is to be prepared with relevant topics to deal with various possible questions that follow.

This is a very classic question, very similar to why String is immutable in Java; the similarity between these two questions is that they are mainly due to design decisions by the creators of Java.

Why Java does not support multiple inheritance, you can consider the following two points:

1) The first reason is the ambiguity surrounding the diamond-shaped inheritance issue, consider a class A that has a foo() method, and then B and C derive from A, and have their own foo() Implementation, now class D uses multiple inheritance derived from B and C, if we only reference foo(), the compiler will not be able to decide which foo() it should call. This is also called the Diamond problem because the structure of this inheritance scheme is similar to a diamond, see below:

                A foo()    
               / \    
             /     \    
 foo() B     C foo()    
             \     /    
               \ /    
               D  foo()
Copy after login

Even if we remove the top A class of the diamond and allow multiple inheritance, we will see this problem ambiguity side. If you tell the interviewer this reason, he will ask why C can support multiple inheritance but Java cannot. Well, in this case I would try to explain to him the second reason I give below, it is not because of technical difficulty, but more maintainability and clearer design are the driving factors, although this only Can be confirmed by Java language designers, we are just speculating. The Wikipedia link has some good explanations of how the problem of different language addresses arises due to the diamond problem when using multiple inheritance.

2) The second and more compelling reason for me is that multiple inheritance does complicate the design and create problems during conversions, constructor chaining, etc. Assuming that there are not many situations where you need multiple inheritance, for the sake of simplicity, the wise decision is to omit it. Additionally, Java can avoid this ambiguity by supporting single inheritance using interfaces. Since the interface only has method declarations and does not provide any implementation, there is only one implementation of a specific method, so there won't be any ambiguity. (For a practical and detailed collection of Java interview questions, you can reply to the "Interview Question Aggregation" on the Java Zhiyin official account)

3. Why does Java not support operator overloading?

Another similarly tricky Java question. Why does C support operator overloading but Java does not? Some may say that operators are already overloaded in Java for string concatenation, don't be fooled by these arguments.

Unlike C, Java does not support operator overloading. Java does not provide programmers with free overloading of standard arithmetic operators such as , - , * and / etc. If you have used C before, then Java lacks many features compared to C. For example, Java does not support multiple inheritance, there are no pointers in Java, and there is no reference passing in Java. Another similar question is about Java passing by reference, which mainly shows whether Java passes parameters by value or reference. Although I don't know the real reason behind it, I think there is some truth to the following statement, why Java does not support operator overloading.

1) Simplicity and clarity. Clarity is one of the goals of Java designers. Rather than just copying the language, the designers wanted to have a clear, truly object-oriented language. Adding operator overloading will definitely make the design more complex than without it, and it may result in a more complex compiler, or slow down the JVM because it requires extra work to identify what the operator actually means and reduces the opportunities for optimization, to Guaranteed operator behavior in Java.

2) Avoid programming errors. Java does not allow user-defined operator overloading because if programmers are allowed to do operator overloading, multiple meanings will be given to the same operator, which will steepen the learning curve for any developer and make things more confusing. It has been observed that when a language supports operator overloading, programming errors increase, thereby increasing development and delivery time. Since Java and the JVM already shoulder most of the developer's responsibility when it comes to memory management by providing a garbage collector, it doesn't make much sense since this feature increases the chance of polluting the code and becoming a source of programming errors.

3) JVM complexity. From a JVM perspective, supporting operator overloading makes the problem more difficult. The same thing can be achieved in a more intuitive and cleaner way using method overloading, so it makes sense not to support operator overloading in Java. Compared to a relatively simple JVM, a complex JVM can result in a slower JVM and less opportunity to optimize code to ensure deterministic operator behavior in Java.

4) Make it easier for development tools to handle. This is another benefit of not supporting operator overloading in Java. Omitting operator overloading makes the language easier to work with, which in turn makes it easier to develop tools for working with the language, such as IDEs or refactoring tools. Refactoring tools are far better in Java than in C.

4. Why is String immutable in Java?

My favorite Java interview questions, tricky but also very useful. Some interviewers also often ask this question, why is String final in Java.

Strings are immutable in Java because String objects are cached in the String pool. Because cached strings are shared among multiple customers, there is always a risk that actions by one customer will affect all other customers. For example, if a piece of code changes the value of String "Test" to "TEST", all other clients will also see that value. Since caching performance of String objects is an important aspect, avoid this risk by making the String class immutable.

同时,String 是 final 的,因此没有人可以通过扩展和覆盖行为来破坏 String 类的不变性、缓存、散列值的计算等。String 类不可变的另一个原因可能是由于 HashMap。

由于把字符串作为 HashMap 键很受欢迎。对于键值来说,重要的是它们是不可变的,以便用它们检索存储在 HashMap 中的值对象。由于 HashMap 的工作原理是散列,因此需要具有相同的值才能正常运行。如果在插入后修改了 String 的内容,可变的 String将在插入和检索时生成两个不同的哈希码,可能会丢失 Map 中的值对象。

如果你是印度板球迷,你可能能够与我的下一句话联系起来。字符串是Java的 VVS Laxman,即非常特殊的类。我还没有看到一个没有使用 String 编写的 Java 程序。这就是为什么对 String 的充分理解对于 Java 开发人员来说非常重要。

String 作为数据类型,传输对象和中间人角色的重要性和流行性也使这个问题在 Java 面试中很常见。

为什么 String 在 Java 中是不可变的是 Java 中最常被问到的字符串访问问题之一,它首先讨论了什么是 String,Java 中的 String 如何与 C 和 C++ 中的 String 不同,然后转向在Java中什么是不可变对象,不可变对象有什么好处,为什么要使用它们以及应该使用哪些场景。

这个问题有时也会问:“为什么 String 在 Java 中是 final 的”。在类似的说明中,如果你正在准备Java 面试,我建议你看看《Java程序员面试宝典(第4版) 》,这是高级和中级Java程序员的优秀资源。它包含来自所有重要 Java 主题的问题,包括多线程,集合,GC,JVM内部以及 Spring和 Hibernate 框架等。

正如我所说,这个问题可能有很多可能的答案,而 String 类的唯一设计者可以放心地回答它。我在 Joshua Bloch 的 Effective Java 书中期待一些线索,但他也没有提到它。我认为以下几点解释了为什么 String 类在 Java 中是不可变的或 final 的:

1)想象字符串池没有使字符串不可变,它根本不可能,因为在字符串池的情况下,一个字符串对象/文字,例如 “Test” 已被许多参考变量引用,因此如果其中任何一个更改了值,其他参数将自动受到影响,即假设

String A="Test";
String B="Test";
Copy after login

现在字符串 B 调用 "Test".toUpperCase(), 将同一个对象改为“TEST”,所以 A 也是 “TEST”,这不是期望的结果。

下图显示了如何在堆内存和字符串池中创建字符串。

Do you know these 10 difficult Java interview questions?

2)字符串已被广泛用作许多 Java 类的参数,例如,为了打开网络连接,你可以将主机名和端口号作为字符串传递,你可以将数据库 URL 作为字符串传递, 以打开数据库连接,你可以通过将文件名作为参数传递给 File I/O 类来打开 Java 中的任何文件。如果 String 不是不可变的,这将导致严重的安全威胁,我的意思是有人可以访问他有权授权的任何文件,然后可以故意或意外地更改文件名并获得对该文件的访问权限。由于不变性,你无需担心这种威胁。这个原因也说明了,为什么 String 在 Java 中是最终的,通过使 java.lang.String final,Java设计者确保没有人覆盖 String 类的任何行为。

3)由于 String 是不可变的,它可以安全地共享许多线程,这对于多线程编程非常重要. 并且避免了 Java 中的同步问题,不变性也使得String 实例在 Java 中是线程安全的,这意味着你不需要从外部同步 String 操作。关于 String 的另一个要点是由截取字符串 SubString 引起的内存泄漏,这不是与线程相关的问题,但也是需要注意的。

4)为什么 String 在 Java 中是不可变的另一个原因是允许 String 缓存其哈希码,Java 中的不可变 String 缓存其哈希码,并且不会在每次调用 String 的 hashcode 方法时重新计算,这使得它在 Java 中的 HashMap 中使用的 HashMap 键非常快。简而言之,因为 String 是不可变的,所以没有人可以在创建后更改其内容,这保证了 String 的 hashCode 在多次调用时是相同的。

5)String 不可变的绝对最重要的原因是它被类加载机制使用,因此具有深刻和基本的安全考虑。如果 String 是可变的,加载“java.io.Writer” 的请求可能已被更改为加载 “mil.vogoon.DiskErasingWriter”. 安全性和字符串池是使字符串不可变的主要原因。顺便说一句,上面的理由很好回答另一个Java面试问题: “为什么String在Java中是最终的”。要想是不可变的,你必须是最终的,这样你的子类不会破坏不变性。你怎么看?

5.为什么 char 数组比 Java 中的 String 更适合存储密码?

另一个基于 String 的棘手 Java 问题,相信我只有很少的 Java 程序员可以正确回答这个问题。这是一个真正艰难的核心Java面试问题,并且需要对 String 的扎实知识才能回答这个问题。

这是最近在 Java 面试中向我的一位朋友询问的问题。他正在接受技术主管职位的面试,并且有超过6年的经验。如果你还没有遇到过这种情况,那么字符数组和字符串可以用来存储文本数据,但是选择一个而不是另一个很难。但正如我的朋友所说,任何与 String 相关的问题都必须对字符串的特殊属性有一些线索,比如不变性,他用它来说服访提问的人。在这里,我们将探讨为什么你应该使用char[]存储密码而不是String的一些原因。

字符串:

1)由于字符串在 Java 中是不可变的,如果你将密码存储为纯文本,它将在内存中可用,直到垃圾收集器清除它. 并且为了可重用性,会存在 String 在字符串池中, 它很可能会保留在内存中持续很长时间,从而构成安全威胁。

由于任何有权访问内存转储的人都可以以明文形式找到密码,这是另一个原因,你应该始终使用加密密码而不是纯文本。由于字符串是不可变的,所以不能更改字符串的内容,因为任何更改都会产生新的字符串,而如果你使用char[],你就可以将所有元素设置为空白或零。因此,在字符数组中存储密码可以明显降低窃取密码的安全风险。

2)Java 本身建议使用 JPasswordField 的 getPassword() 方法,该方法返回一个 char[] 和不推荐使用的getTex() 方法,该方法以明文形式返回密码,由于安全原因。应遵循 Java 团队的建议, 坚持标准而不是反对它。

3)使用 String 时,总是存在在日志文件或控制台中打印纯文本的风险,但如果使用 Array,则不会打印数组的内容而是打印其内存位置。虽然不是一个真正的原因,但仍然有道理。

    String strPassword =“Unknown”; 
    char [] charPassword = new char [] {'U','n','k','w','o','n'}; 
    System.out.println(“字符密码:”+ strPassword);
    System.out.println(“字符密码:”+ charPassword);
Copy after login

输出

字符串密码:Unknown
字符密码:[C @110b053
Copy after login

我还建议使用散列或加密的密码而不是纯文本,并在验证完成后立即从内存中清除它。因此,在Java中,用字符数组用存储密码比字符串是更好的选择。虽然仅使用char[]还不够,还你需要擦除内容才能更安全。(实用详尽的Java面试题大全,可以在Java知音公众号回复“面试题聚合”)

6.如何使用双重检查锁定在 Java 中创建线程安全的单例?

这个 Java 问题也常被问: 什么是线程安全的单例,你怎么创建它。好吧,在Java 5之前的版本, 使用双重检查锁定创建单例 Singleton 时,如果多个线程试图同时创建 Singleton 实例,则可能有多个 Singleton 实例被创建。从 Java 5 开始,使用 Enum 创建线程安全的Singleton很容易。但如果面试官坚持双重检查锁定,那么你必须为他们编写代码。记得使用volatile变量。

为什么枚举单例在 Java 中更好

枚举单例是使用一个实例在 Java 中实现单例模式的新方法。虽然Java中的单例模式存在很长时间,但枚举单例是相对较新的概念,在引入Enum作为关键字和功能之后,从Java5开始在实践中。本文与之前关于 Singleton 的内容有些相关, 其中讨论了有关 Singleton 模式的面试中的常见问题, 以及 10 个 Java 枚举示例, 其中我们看到了如何通用枚举可以。这篇文章是关于为什么我们应该使用Eeame作为Java中的单例,它比传统的单例方法相比有什么好处等等。

Java 枚举和单例模式

Java 中的枚举单例模式是使用枚举在 Java 中实现单例模式。单例模式在 Java 中早有应用, 但使用枚举类型创建单例模式时间却不长. 如果感兴趣, 你可以了解下构建者设计模式和装饰器设计模式。

1) 枚举单例易于书写

这是迄今为止最大的优势,如果你在Java 5之前一直在编写单例, 你知道, 即使双检查锁定, 你仍可以有多个实例。虽然这个问题通过 Java 内存模型的改进已经解决了, 从 Java 5 开始的 volatile 类型变量提供了保证, 但是对于许多初学者来说, 编写起来仍然很棘手。与同步双检查锁定相比,枚举单例实在是太简单了。如果你不相信, 那就比较一下下面的传统双检查锁定单例和枚举单例的代码:

在 Java 中使用枚举的单例

这是我们通常声明枚举的单例的方式,它可能包含实例变量和实例方法,但为了简单起见,我没有使用任何实例方法,只是要注意,如果你使用的实例方法且该方法能改变对象的状态的话, 则需要确保该方法的线程安全。默认情况下,创建枚举实例是线程安全的,但 Enum 上的任何其他方法是否线程安全都是程序员的责任。

/**
* 使用 Java 枚举的单例模式示例
*/
public enum EasySingleton{
    INSTANCE;
}
Copy after login

你可以通过EasySingleton.INSTANCE来处理它,这比在单例上调用getInstance()方法容易得多。

具有双检查锁定的单例示例

下面的代码是单例模式中双重检查锁定的示例,此处的 getInstance() 方法检查两次,以查看 INSTANCE 是否为空,这就是为什么它被称为双检查锁定模式,请记住,双检查锁定是代理之前Java 5,但Java5内存模型中易失变量的干扰,它应该工作完美。

/**
* 单例模式示例,双重锁定检查
*/
public class DoubleCheckedLockingSingleton{
     private volatile DoubleCheckedLockingSingleton INSTANCE;

     private DoubleCheckedLockingSingleton(){}

     public DoubleCheckedLockingSingleton getInstance(){
         if(INSTANCE == null){
            synchronized(DoubleCheckedLockingSingleton.class){
                //double checking Singleton instance
                if(INSTANCE == null){
                    INSTANCE = new DoubleCheckedLockingSingleton();
                }
            }
         }
         return INSTANCE;
     }
}
Copy after login

你可以调用DoubleCheckedLockingSingleton.getInstance() 来获取此单例类的访问权限。

现在,只需查看创建延迟加载的线程安全的 Singleton 所需的代码量。使用枚举单例模式, 你可以在一行中具有该模式, 因为创建枚举实例是线程安全的, 并且由 JVM 进行。

人们可能会争辩说,有更好的方法来编写 Singleton 而不是双检查锁定方法, 但每种方法都有自己的优点和缺点, 就像我最喜欢在类加载时创建的静态字段 Singleton, 如下面所示, 但请记住, 这不是一个延迟加载单例:

单例模式用静态工厂方法

这是我最喜欢的在 Java 中影响 Singleton 模式的方法之一,因为 Singleton 实例是静态的,并且最后一个变量在类首次加载到内存时初始化,因此实例的创建本质上是线程安全的。

/**
* 单例模式示例与静态工厂方法
*/
public class Singleton{
    //initailzed during class loading
    private static final Singleton INSTANCE = new Singleton();

    //to prevent creating another instance of Singleton
    private Singleton(){}

    public static Singleton getSingleton(){
        return INSTANCE;
    }
}
Copy after login

你可以调用 Singleton.getSingleton() 来获取此类的访问权限。

2) 枚举单例自行处理序列化

传统单例的另一个问题是,一旦实现可序列化接口,它们就不再是 Singleton, 因为 readObject() 方法总是返回一个新实例, 就像 Java 中的构造函数一样。通过使用 readResolve() 方法, 通过在以下示例中替换 Singeton 来避免这种情况:

//readResolve to prevent another instance of Singleton
private Object readResolve(){
    return INSTANCE;
}
Copy after login

如果 Singleton 类保持内部状态, 这将变得更加复杂, 因为你需要标记为 transient(不被序列化),但使用枚举单例, 序列化由 JVM 进行。

3) 创建枚举实例是线程安全的

如第 1 点所述,因为 Enum 实例的创建在默认情况下是线程安全的, 你无需担心是否要做双重检查锁定。

总之, 在保证序列化和线程安全的情况下,使用两行代码枚举单例模式是在 Java 5 以后的世界中创建 Singleton 的最佳方式。你仍然可以使用其他流行的方法, 如你觉得更好, 欢迎讨论。

7. 编写 Java 程序时, 如何在 Java 中创建死锁并修复它?

经典但核心Java面试问题之一。

如果你没有参与过多线程并发 Java 应用程序的编码,你可能会失败。

(视频教程推荐:java课程

如何避免 Java 线程死锁?

如何避免 Java 中的死锁?是 Java 面试的热门问题之一, 也是多线程的编程中的重口味之一, 主要在招高级程序员时容易被问到, 且有很多后续问题。尽管问题看起来非常基本, 但大多数 Java 开发人员一旦你开始深入, 就会陷入困境。

面试问题总是以“什么是死锁?”开始

当两个或多个线程在等待彼此释放所需的资源(锁定)并陷入无限等待即是死锁。它仅在多任务或多线程的情况下发生。

如何检测 Java 中的死锁?

虽然这可以有很多答案, 但我的版本是首先我会看看代码, 如果我看到一个嵌套的同步块,或从一个同步的方法调用其他同步方法, 或试图在不同的对象上获取锁, 如果开发人员不是非常小心,就很容易造成死锁。

另一种方法是在运行应用程序时实际锁定时找到它, 尝试采取线程转储,在 Linux 中,你可以通过kill -3命令执行此操作, 这将打印应用程序日志文件中所有线程的状态, 并且你可以看到哪个线程被锁定在哪个线程对象上。

你可以使用 fastthread.io 网站等工具分析该线程转储, 这些工具允许你上载线程转储并对其进行分析。

另一种方法是使用 jConsole 或 VisualVM, 它将显示哪些线程被锁定以及哪些对象被锁定。

如果你有兴趣了解故障排除工具和分析线程转储的过程, 我建议你看看 Uriah Levy 在多元视觉(PluraIsight)上《分析 Java 线程转储》课程。旨在详细了解 Java 线程转储, 并熟悉其他流行的高级故障排除工具。

()

编写一个将导致死锁的Java程序?

一旦你回答了前面的问题,他们可能会要求你编写代码,这将导致Java死锁。

这是我的版本之一

/**
 * Java 程序通过强制循环等待来创建死锁。
 *
 *
 */
public class DeadLockDemo {

    /*
     * 此方法请求两个锁,第一个字符串,然后整数
     */
     public void method1() {
        synchronized (String.class) {
            System.out.println("Aquired lock on String.class object");

            synchronized (Integer.class) {
                System.out.println("Aquired lock on Integer.class object");
            }
        }
    }


    /*
     * 此方法也请求相同的两个锁,但完全
     * 相反的顺序,即首先整数,然后字符串。
     * 如果一个线程持有字符串锁,则这会产生潜在的死锁
     * 和其他持有整数锁,他们等待对方,永远。
     */
     public void method2() {
        synchronized (Integer.class) {
            System.out.println("Aquired lock on Integer.class object");

            synchronized (String.class) {
                System.out.println("Aquired lock on String.class object");
            }
        }
    }
}
Copy after login

如果 method1() 和 method2() 都由两个或多个线程调用,则存在死锁的可能性, 因为如果线程 1 在执行 method1() 时在 Sting 对象上获取锁, 线程 2 在执行 method2() 时在 Integer 对象上获取锁, 等待彼此释放 Integer 和 String 上的锁以继续进行一步, 但这永远不会发生。

Do you know these 10 difficult Java interview questions?

此图精确演示了我们的程序, 其中一个线程在一个对象上持有锁, 并等待其他线程持有的其他对象锁。

你可以看到, Thread1 需要 Thread2 持有的 Object2 上的锁,而 Thread2 希望获得 Thread1 持有的 Object1 上的锁。由于没有线程愿意放弃, 因此存在死锁, Java 程序被卡住。

其理念是, 你应该知道使用常见并发模式的正确方法, 如果你不熟悉这些模式,那么 Jose Paumard 《应用于并发和多线程的常见 Java 模式》是学习的好起点。

如何避免Java中的死锁?

现在面试官来到最后一部分, 在我看来, 最重要的部分之一; 如何修复代码中的死锁?或如何避免Java中的死锁?

如果你仔细查看了上面的代码,那么你可能已经发现死锁的真正原因不是多个线程, 而是它们请求锁的方式, 如果你提供有序访问, 则问题将得到解决。

下面是我的修复版本,它通过避免循环等待,而避免死锁, 而不需要抢占, 这是需要死锁的四个条件之一。

public class DeadLockFixed {

    /**
     * 两种方法现在都以相同的顺序请求锁,首先采用整数,然后是 String。
     * 你也可以做反向,例如,第一个字符串,然后整数,
     * 只要两种方法都请求锁定,两者都能解决问题
     * 顺序一致。
     */
    public void method1() {
        synchronized (Integer.class) {
            System.out.println("Aquired lock on Integer.class object");

            synchronized (String.class) {
                System.out.println("Aquired lock on String.class object");
            }
        }
    }

    public void method2() {
        synchronized (Integer.class) {
            System.out.println("Aquired lock on Integer.class object");

            synchronized (String.class) {
                System.out.println("Aquired lock on String.class object");
            }
        }
    }
}
Copy after login

现在没有任何死锁,因为两种方法都按相同的顺序访问 Integer 和 String 类文本上的锁。因此,如果线程 A 在 Integer 对象上获取锁, 则线程 B 不会继续, 直到线程 A 释放 Integer 锁, 即使线程 B 持有 String 锁, 线程 A 也不会被阻止, 因为现在线程 B 不会期望线程 A 释放 Integer 锁以继续。(实用详尽的Java面试题大全,可以在Java知音公众号回复“面试题聚合”)

8. 如果你的Serializable类包含一个不可序列化的成员,会发生什么?你是如何解决的?

任何序列化该类的尝试都会因NotSerializableException而失败,但这可以通过在 Java中 为 static 设置瞬态(trancient)变量来轻松解决。

Java 序列化相关的常见问题

Java 序列化是一个重要概念, 但它很少用作持久性解决方案, 开发人员大多忽略了 Java 序列化 API。根据我的经验, Java 序列化在任何 Java核心内容面试中都是一个相当重要的话题, 在几乎所有的网面试中, 我都遇到过一两个 Java 序列化问题, 我看过一次面试, 在问几个关于序列化的问题之后候选人开始感到不自在, 因为缺乏这方面的经验。

他们不知道如何在 Java 中序列化对象, 或者他们不熟悉任何 Java 示例来解释序列化, 忘记了诸如序列化在 Java 中如何工作, 什么是标记接口, 标记接口的目的是什么, 瞬态变量和可变变量之间的差异, 可序列化接口具有多少种方法, 在 Java 中,Serializable 和 Externalizable 有什么区别, 或者在引入注解之后, 为什么不用 @Serializable 注解或替换 Serializalbe 接口。

Do you know these 10 difficult Java interview questions?

在本文中,我们将从初学者和高级别进行提问, 这对新手和具有多年 Java 开发经验的高级开发人员同样有益。

关于Java序列化的10个面试问题

大多数商业项目使用数据库或内存映射文件或只是普通文件, 来满足持久性要求, 只有很少的项目依赖于 Java 中的序列化过程。无论如何,这篇文章不是 Java 序列化教程或如何序列化在 Java 的对象, 但有关序列化机制和序列化 API 的面试问题, 这是值得去任何 Java 面试前先看看以免让一些未知的内容惊到自己。

For those who are not familiar with Java serialization, Java serialization is the process used to serialize objects in Java by storing the state of the object to a file with a .ser extension, and can be restored through this file Rebuilding the Java object state, this reverse process is called deserialization.

What is Java serialization

Serialization is the process of changing an object into a binary format that can be saved to disk or sent over the network to other running Java virtual machines, and can be reversed Serialization restores object state. The Java serialization API provides developers with a standard mechanism to handle object serialization through the java.io.Serializable and java.io.Externalizable interfaces, ObjectInputStream and ObjectOutputStream. Java programmers are free to choose based on class structure standard serialization or their own custom binary format, the latter is generally considered the best practice because the serialized binary file format becomes part of the class output API, potentially breaking the encapsulation of private and package-visible properties in Java.

How to serialize

It is very simple to make classes in Java serializable. Your Java class only needs to implement the java.io.Serializable interface, and the JVM will serialize the Object object in the default format. Making a class serializable requires intentionality. Making a class serializable can be a long-term cost, and may therefore restrict you from modifying or changing its implementation. When you change the structure of a class by adding an interface through the implementation , adding or removing any fields may break the default serialization, which can minimize the possibility of incompatibility through custom binary formats, but still requires significant effort to ensure backward compatibility. One example of how serialization limits your ability to change a class is SerialVersionUID.

If you do not declare SerialVersionUID explicitly, the JVM generates its structure based on the class structure, which depends on the class implementation interface and several other factors that may change. Assuming that your new version of the class file implements another interface, the JVM will generate a different SerialVersionUID and when you try to load the old object serialized by the old version of the program, you will get an InvalidClassException.

Question 1) What is the difference between serializable interface and external interface in Java?

This is the most frequently asked question in Java serialization interviews. Below is my version Externalizable provides us with writeExternal() and readExternal() methods, which gives us flexible control over Java serialization mechanism instead of relying on Java's default serialization. Properly implementing the Externalizable interface can significantly improve the performance of your application.

Question 2) How many serializable methods are there? What is the purpose of a serializable interface if it has no methods?

Serializable The Serializalbe interface exists in the java.io package and forms the core of the Java serialization mechanism. It does not have any methods, also known as tagged interface in Java. When a class implements the java.io.Serializable interface, it becomes serializable in Java and instructs the compiler to serialize this object using the Java serialization mechanism.

Question 3) What is serialVersionUID? What happens if you don't define this?

One of my favorite interview questions is about Java serialization. serialVersionUID is a private static final long ID. When it is printed on the object, it is usually the hash code of the object. You can use the JDK tool serialver to view the serialVersionUID of the serialized object. SerialVerionUID is used for object versioning. The serialVersionUID can also be specified in the class file. The consequence of not specifying serialVersionUID is that when you add or modify any field in the class, then the serialized class will not be restored because the serialVersionUID generated for the new class and the old serialized object will be different. The Java serialization process relies on the correct serialization of the object to restore the state, and throws a java.io.InvalidClassException if the serial version of the serialized object does not match. For more information about serialVersionUID, please refer to this article, FQ required.

Question 4) When serializing, do you want some members not to be serialized? How do you implement it?

Another frequently asked serialization interview question. This is also sometimes asked, like what is a transient variable, will transient and static variables get serialized, etc. So, if you don't want any field to be part of the state of the object, then declare it static or transient Depending on your needs, this will not be included in the Java serialization process.

Question 5) What happens if a member of the class does not implement the serializable interface?

A simple question about the Java serialization process. If you try to serialize an object of a class that implements Serializable, but the object contains a reference to a non-Serializable class, a NotSerializableException will be thrown at runtime, which is why I always put a Serializable alert (in (in my Code Comments section), one of the code comment best practices instructs developers to keep this fact in mind when adding new fields in serializable classes.

Question 6) If a class is serializable, but its superclass is not, what is the state of instance variables inherited from the superclass after deserialization?

Java serialization process continues only if the object hierarchy is a serializable structure, that is, the serializable interface in Java is implemented, and the value of the instance variable inherited from the super class will be constructed by calling Function initialization, superclass that is not serializable during deserialization. Once the constructor chaining will start, it will not be possible to stop, so the constructor will be executed even if a class higher in the hierarchy implements the serializable interface. As you can see from the statement, this serialization interview question looks very tricky and difficult, but it is not difficult if you are familiar with the key concepts.

Question 7) Is it possible to customize the serialization process, or is it possible to override the default serialization process in Java?

The answer is yes, you can. We all know that to serialize an object, you need to call ObjectOutputStream.writeObject(saveThisObject), and use ObjectInputStream.readObject() to read the object, but one more thing the Java virtual machine provides you is to define these two methods. If these two methods are defined in the class, the JVM will call these two methods instead of applying the default serialization mechanism. Here you can customize the behavior of object serialization and deserialization by performing any kind of pre- or post-processing tasks.

The important thing to note is to declare these methods as private methods to avoid being inherited, overridden, or overloaded. Since only the Java virtual machine can call private methods of your class, the integrity of your class is preserved, and Java serialization will work properly. In my opinion, this is one of the best questions you can ask in any Java serialization interview, and a good follow-up question is, why provide a custom serialization form for your objects?

Question 8) Assuming that the super class of the new class implements the serializable interface, how to prevent the new class from being serialized?

A tough interview question in Java serialization. If the Super class of a class has implemented the serializable interface in Java, then it is already serializable in Java, since you cannot cancel the interface, it is not possible to actually make the class unserializable, but there is a way to avoid the new Class serialization. To avoid Java serialization, you need to implement writeObject() and readObject() methods in your class, and you need to throw NotSerializableException from this method. This is another benefit of customizing the Java serialization process, as mentioned in the serialization interview question above, and is often asked as a follow-up question as the interview progresses.

Question 9) What methods are used during serialization and deserialization process in Java?

This is a very common interview question, basically the interviewer is trying to know about serialization: Are you familiar with the usage of readObject(), writeObject(), readExternal() and writeExternal(). Java serialization is done by the java.io.ObjectOutputStream class. This class is a filter stream encapsulated in a lower level byte stream to handle the serialization mechanism. To store any object through the serialization mechanism, we call ObjectOutputStream.writeObject(savethisobject), and to deserialize the object, we call the ObjectInputStream.readObject() method. Calling the writeObject() method triggers the serialization process in java. An important thing to note about the readObject() method is that it is used to read bytes from persistence, create an object from those bytes, and return an object that requires a type cast to the correct type.

Question 10) Suppose you have a class that is serialized and stored in persistence, and then you modify the class to add a new field. What happens if you deserialize a serialized object?

This depends on whether the class has its own serialVersionUID. As we know from the above question, if we do not provide the serialVersionUID, then the Java compiler will generate it and usually it is equal to the hash code of the object. By adding any new field, there is a possibility that the new serialVersionUID generated for the new version of the class will be different from the already serialized object, in this case the Java Serialization API will throw a java.io.InvalidClassException, so it is recommended to have your own in the code serialVersionUID, and ensure that it remains constant within a single class.

11) What are the compatible changes and incompatible changes in Java serialization mechanism?

The real challenge lies in changing the class structure by adding any field, method or removing any field or method by using the serialized object. According to the Java Serialization Specification, adding any field or method is subject to incompatible changes and changes to the class hierarchy or de-implementation of serializable interfaces, some of which are subject to incompatible changes. For a complete list of compatible and non-compatible changes, I recommend reading the Java Serialization Specification.

12) Can we transmit a serialized object over the network?

Yes, you can transmit serialized objects over the network, because Java serialized objects are still in the form of bytes, and bytes can be sent over the network. You can also store serialized objects as blobs on disk or in a database.

13) Which variables are not serialized during Java serialization?

This question is asked differently, but the purpose is still the same, do Java developers know the details of static and transient variables. Since static variables belong to classes and not objects, they are not part of the object's state and therefore they are not saved during Java serialization. Since Java serialization only retains the state of the object, not the object itself. Transient variables are also not included in the Java serialization process and are not part of the object's serialized state. After asking this question, the interviewer will ask the follow-up, if you don't store the value of these variables, what is the value of these variables once you deserialize these objects and recreate them? This is what you need to consider.

9. Why does the wait method in Java need to be called in a synchronized method?

Another thorny core Java issue, wait and notify. They are called in synchronized-marked methods or synchronized blocks because wait and modify need to monitor the Object on which wait or notify-get is called.

Most Java developers know that the wait(), notify() and notifyAll() methods of object classes must be called in synchronized methods or synchronized blocks in Java, but how many times have we thought about, why in Does wait, notify and notifyAll come from synchronized blocks or methods in Java?

Recently this question was asked to a friend of mine in a Java interview, he thought about it and replied: If we don't start from the synchronized context When calling wait() or notify() method in Java, we will receive IllegalMonitorStateException in Java.

His answer is actually correct, but the interviewer will not be completely satisfied with this answer and wants to explain the problem to him. After the interview he and I discussed the same issue and I thought he should tell the interviewer about the race condition between wait() and notify() in Java, which may exist if we don't call them in synchronized methods or blocks.

Let’s see how race conditions occur in Java programs. It is also one of the popular threaded interview questions and comes up frequently in both phone and in-person Java developer interviews. So, if you are preparing for a Java interview, then you should prepare for questions like this, and one book that can really help you is Java Programmer Interview Formula Book. This is a rare book that covers almost all important topics in Java interviews such as core Java, multi-threading, IO and NIO and frameworks like Spring and Hibernate. You can check it out here.

Do you know these 10 difficult Java interview questions?

Why wait method from synchronized method in Java Why must be called from synchronized block or method in Java? We mainly use wait(), notify() or notifyAll() methods for inter-thread communication in Java. A thread is waiting after checking a condition, for example, in the classic producer-consumer problem, if the buffer is full, the producer thread waits and the consumer thread notifies the producer after creating space in the buffer by using elements or thread. Call the notify() or notifyAll() method to notify single or multiple threads that a condition has changed, and once the notifying thread leaves the synchronized block, all waiting threads start to acquire the waiting object lock, and the lucky thread reacquires After locking, return from the wait() method and continue.

Let us break the whole operation into steps to see the possibility of race condition between wait() and notify() methods in Java, we will use Produce Consumer thread example to better understand the scenario:

  • The Producer thread tests the condition (whether the buffer is complete) and confirms that it must wait (finding that the buffer is full).

  • Consumer thread sets the condition after consuming the elements in the buffer.

  • The Consumer thread calls the notify() method; this will not be heard because the Producer thread is not waiting yet.

  • The Producer thread calls the wait() method and enters the waiting state.

So we may lose notifications due to race conditions, if we use a buffer or only use one element, the production thread will wait forever and your program will hang. "Waiting for notify and notifyall in java synchronization Now let us consider how to solve this potential race condition?

This race condition is solved by using the synchronized keyword and lock provided by Java. In order to call wait() , notify() or notifyAll(), in Java, we have to acquire the lock on the object on which we call the method. Since the wait() method in Java releases the lock before waiting and reacquires the lock before returning from wait() method , we have to use this lock to ensure that checking the condition (whether the buffer is full) and setting the condition (getting the element from the buffer) are atomic, this can be achieved by using synchronized methods or blocks in Java.

我不确定这是否是面试官实际期待的,但这个我认为至少有意义,请纠正我如果我错了,请告诉我们是否还有其他令人信服的理由调用 wait(),notify() 或 Java 中的 notifyAll() 方法。

总结一下,我们用 Java 中的 synchronized 方法或 synchronized 块调用 Java 中的 wait(),notify() 或 notifyAll() 方法来避免:

1) Java 会抛出 IllegalMonitorStateException,如果我们不调用来自同步上下文的wait(),notify()或者notifyAll()方法。

2) Javac 中 wait 和 notify 方法之间的任何潜在竞争条件。

10.你能用Java覆盖静态方法吗?如果我在子类中创建相同的方法是编译时错误?

不,你不能在Java中覆盖静态方法,但在子类中声明一个完全相同的方法不是编译时错误,这称为隐藏在Java中的方法。

你不能覆盖Java中的静态方法,因为方法覆盖基于运行时的动态绑定,静态方法在编译时使用静态绑定进行绑定。虽然可以在子类中声明一个具有相同名称和方法签名的方法,看起来可以在Java中覆盖静态方法,但实际上这是方法隐藏。Java不会在运行时解析方法调用,并且根据用于调用静态方法的 Object 类型,将调用相应的方法。这意味着如果你使用父类的类型来调用静态方法,那么原始静态将从父类中调用,另一方面如果你使用子类的类型来调用静态方法,则会调用来自子类的方法。简而言之,你无法在Java中覆盖静态方法。如果你使用像Eclipse或Netbeans这样的Java IDE,它们将显示警告静态方法应该使用类名而不是使用对象来调用,因为静态方法不能在Java中重写。

/**
 *
 * Java program which demonstrate that we can not override static method in Java.
 * Had Static method can be overridden, with Super class type and sub class object
 * static method from sub class would be called in our example, which is not the case.
 */
public class CanWeOverrideStaticMethod {

    public static void main(String args[]) {

        Screen scrn = new ColorScreen();

        //if we can  override static , this should call method from Child class
        scrn.show(); //IDE will show warning, static method should be called from classname

    } 

}

class Screen{ 
    /*
     * public static method which can not be overridden in Java
     */
    public static void show(){
        System.out.printf("Static method from parent class");
    }
}

class ColorScreen extends Screen{
    /*
     * static method of same name and method signature as existed in super
     * class, this is not method overriding instead this is called
     * method hiding in Java
     */
    public static void show(){
        System.err.println("Overridden static method in Child Class in Java");
    }
}
Copy after login

输出:

Static method from parent class

此输出确认你无法覆盖Java中的静态方法,并且静态方法基于类型信息而不是基于Object进行绑定。如果要覆盖静态mehtod,则会调用子类或 ColorScreen 中的方法。这一切都在讨论中我们可以覆盖Java中的静态方法。我们已经确认没有,我们不能覆盖静态方法,我们只能在Java中隐藏静态方法。创建具有相同名称和mehtod签名的静态方法称为Java隐藏方法。IDE将显示警告:"静态方法应该使用类名而不是使用对象来调用", 因为静态方法不能在Java中重写。

这些是我的核心Java面试问题和答案的清单。对于有经验的程序员来说,一些Java问题看起来并不那么难,但对于Java中的中级和初学者来说,它们真的很难回答。顺便说一句,如果你在面试中遇到任何棘手的Java问题,请与我们分享。

相关推荐:java入门教程

The above is the detailed content of Do you know these 10 difficult Java interview questions?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template