国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1. Why are waits and notifications declared in the Object class instead of Thread?
2. Why is multiple inheritance not supported in Java?
3. Why does Java not support operator overloading?
4. Why is String immutable in Java?
5.為什么 char 數(shù)組比 Java 中的 String 更適合存儲密碼?
6.如何使用雙重檢查鎖定在 Java 中創(chuàng)建線程安全的單例?
7. 編寫 Java 程序時, 如何在 Java 中創(chuàng)建死鎖并修復它?
8. 如果你的Serializable類包含一個不可序列化的成員,會發(fā)生什么?你是如何解決的?
9. Why does the wait method in Java need to be called in a synchronized method?
10.你能用Java覆蓋靜態(tài)方法嗎?如果我在子類中創(chuàng)建相同的方法是編譯時錯誤?
Home Java JavaInterview questions Do you know these 10 difficult Java interview questions?

Do you know these 10 difficult Java interview questions?

Sep 19, 2020 pm 05:11 PM
java Interview questions

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()

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 中的值對象。

如果你是印度板球迷,你可能能夠與我的下一句話聯(lián)系起來。字符串是Java的 VVS Laxman,即非常特殊的類。我還沒有看到一個沒有使用 String 編寫的 Java 程序。這就是為什么對 String 的充分理解對于 Java 開發(fā)人員來說非常重要。

String 作為數(shù)據(jù)類型,傳輸對象和中間人角色的重要性和流行性也使這個問題在 Java 面試中很常見。

為什么 String 在 Java 中是不可變的是 Java 中最常被問到的字符串訪問問題之一,它首先討論了什么是 String,Java 中的 String 如何與 C 和 C++ 中的 String 不同,然后轉向在Java中什么是不可變對象,不可變對象有什么好處,為什么要使用它們以及應該使用哪些場景。

這個問題有時也會問:“為什么 String 在 Java 中是 final 的”。在類似的說明中,如果你正在準備Java 面試,我建議你看看《Java程序員面試寶典(第4版) 》,這是高級和中級Java程序員的優(yōu)秀資源。它包含來自所有重要 Java 主題的問題,包括多線程,集合,GC,JVM內部以及 Spring和 Hibernate 框架等。

正如我所說,這個問題可能有很多可能的答案,而 String 類的唯一設計者可以放心地回答它。我在 Joshua Bloch 的 Effective Java 書中期待一些線索,但他也沒有提到它。我認為以下幾點解釋了為什么 String 類在 Java 中是不可變的或 final 的:

1)想象字符串池沒有使字符串不可變,它根本不可能,因為在字符串池的情況下,一個字符串對象/文字,例如 “Test” 已被許多參考變量引用,因此如果其中任何一個更改了值,其他參數(shù)將自動受到影響,即假設

String A="Test";
String B="Test";

現(xiàn)在字符串 B 調用 "Test".toUpperCase(), 將同一個對象改為“TEST”,所以 A 也是 “TEST”,這不是期望的結果。

下圖顯示了如何在堆內存和字符串池中創(chuàng)建字符串。

Do you know these 10 difficult Java interview questions?

2)字符串已被廣泛用作許多 Java 類的參數(shù),例如,為了打開網(wǎng)絡連接,你可以將主機名和端口號作為字符串傳遞,你可以將數(shù)據(jù)庫 URL 作為字符串傳遞, 以打開數(shù)據(jù)庫連接,你可以通過將文件名作為參數(shù)傳遞給 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 是不可變的,所以沒有人可以在創(chuàng)建后更改其內容,這保證了 String 的 hashCode 在多次調用時是相同的。

5)String 不可變的絕對最重要的原因是它被類加載機制使用,因此具有深刻和基本的安全考慮。如果 String 是可變的,加載“java.io.Writer” 的請求可能已被更改為加載 “mil.vogoon.DiskErasingWriter”. 安全性和字符串池是使字符串不可變的主要原因。順便說一句,上面的理由很好回答另一個Java面試問題: “為什么String在Java中是最終的”。要想是不可變的,你必須是最終的,這樣你的子類不會破壞不變性。你怎么看?

5.為什么 char 數(shù)組比 Java 中的 String 更適合存儲密碼?

另一個基于 String 的棘手 Java 問題,相信我只有很少的 Java 程序員可以正確回答這個問題。這是一個真正艱難的核心Java面試問題,并且需要對 String 的扎實知識才能回答這個問題。

這是最近在 Java 面試中向我的一位朋友詢問的問題。他正在接受技術主管職位的面試,并且有超過6年的經(jīng)驗。如果你還沒有遇到過這種情況,那么字符數(shù)組和字符串可以用來存儲文本數(shù)據(jù),但是選擇一個而不是另一個很難。但正如我的朋友所說,任何與 String 相關的問題都必須對字符串的特殊屬性有一些線索,比如不變性,他用它來說服訪提問的人。在這里,我們將探討為什么你應該使用char[]存儲密碼而不是String的一些原因。

字符串:

1)由于字符串在 Java 中是不可變的,如果你將密碼存儲為純文本,它將在內存中可用,直到垃圾收集器清除它. 并且為了可重用性,會存在 String 在字符串池中, 它很可能會保留在內存中持續(xù)很長時間,從而構成安全威脅。

由于任何有權訪問內存轉儲的人都可以以明文形式找到密碼,這是另一個原因,你應該始終使用加密密碼而不是純文本。由于字符串是不可變的,所以不能更改字符串的內容,因為任何更改都會產(chǎn)生新的字符串,而如果你使用char[],你就可以將所有元素設置為空白或零。因此,在字符數(shù)組中存儲密碼可以明顯降低竊取密碼的安全風險。

2)Java 本身建議使用 JPasswordField 的 getPassword() 方法,該方法返回一個 char[] 和不推薦使用的getTex() 方法,該方法以明文形式返回密碼,由于安全原因。應遵循 Java 團隊的建議, 堅持標準而不是反對它。

3)使用 String 時,總是存在在日志文件或控制臺中打印純文本的風險,但如果使用 Array,則不會打印數(shù)組的內容而是打印其內存位置。雖然不是一個真正的原因,但仍然有道理。

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

輸出

字符串密碼:Unknown
字符密碼:[C @110b053

我還建議使用散列或加密的密碼而不是純文本,并在驗證完成后立即從內存中清除它。因此,在Java中,用字符數(shù)組用存儲密碼比字符串是更好的選擇。雖然僅使用char[]還不夠,還你需要擦除內容才能更安全。(實用詳盡的Java面試題大全,可以在Java知音公眾號回復“面試題聚合”)

6.如何使用雙重檢查鎖定在 Java 中創(chuàng)建線程安全的單例?

這個 Java 問題也常被問: 什么是線程安全的單例,你怎么創(chuàng)建它。好吧,在Java 5之前的版本, 使用雙重檢查鎖定創(chuàng)建單例 Singleton 時,如果多個線程試圖同時創(chuàng)建 Singleton 實例,則可能有多個 Singleton 實例被創(chuàng)建。從 Java 5 開始,使用 Enum 創(chuàng)建線程安全的Singleton很容易。但如果面試官堅持雙重檢查鎖定,那么你必須為他們編寫代碼。記得使用volatile變量。

為什么枚舉單例在 Java 中更好

枚舉單例是使用一個實例在 Java 中實現(xiàn)單例模式的新方法。雖然Java中的單例模式存在很長時間,但枚舉單例是相對較新的概念,在引入Enum作為關鍵字和功能之后,從Java5開始在實踐中。本文與之前關于 Singleton 的內容有些相關, 其中討論了有關 Singleton 模式的面試中的常見問題, 以及 10 個 Java 枚舉示例, 其中我們看到了如何通用枚舉可以。這篇文章是關于為什么我們應該使用Eeame作為Java中的單例,它比傳統(tǒng)的單例方法相比有什么好處等等。

Java 枚舉和單例模式

Java 中的枚舉單例模式是使用枚舉在 Java 中實現(xiàn)單例模式。單例模式在 Java 中早有應用, 但使用枚舉類型創(chuàng)建單例模式時間卻不長. 如果感興趣, 你可以了解下構建者設計模式和裝飾器設計模式。

1) 枚舉單例易于書寫

這是迄今為止最大的優(yōu)勢,如果你在Java 5之前一直在編寫單例, 你知道, 即使雙檢查鎖定, 你仍可以有多個實例。雖然這個問題通過 Java 內存模型的改進已經(jīng)解決了, 從 Java 5 開始的 volatile 類型變量提供了保證, 但是對于許多初學者來說, 編寫起來仍然很棘手。與同步雙檢查鎖定相比,枚舉單例實在是太簡單了。如果你不相信, 那就比較一下下面的傳統(tǒng)雙檢查鎖定單例和枚舉單例的代碼:

在 Java 中使用枚舉的單例

這是我們通常聲明枚舉的單例的方式,它可能包含實例變量和實例方法,但為了簡單起見,我沒有使用任何實例方法,只是要注意,如果你使用的實例方法且該方法能改變對象的狀態(tài)的話, 則需要確保該方法的線程安全。默認情況下,創(chuàng)建枚舉實例是線程安全的,但 Enum 上的任何其他方法是否線程安全都是程序員的責任。

/**
* 使用 Java 枚舉的單例模式示例
*/
public enum EasySingleton{
    INSTANCE;
}

你可以通過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;
     }
}

你可以調用DoubleCheckedLockingSingleton.getInstance() 來獲取此單例類的訪問權限。

現(xiàn)在,只需查看創(chuàng)建延遲加載的線程安全的 Singleton 所需的代碼量。使用枚舉單例模式, 你可以在一行中具有該模式, 因為創(chuàng)建枚舉實例是線程安全的, 并且由 JVM 進行。

人們可能會爭辯說,有更好的方法來編寫 Singleton 而不是雙檢查鎖定方法, 但每種方法都有自己的優(yōu)點和缺點, 就像我最喜歡在類加載時創(chuàng)建的靜態(tài)字段 Singleton, 如下面所示, 但請記住, 這不是一個延遲加載單例:

單例模式用靜態(tài)工廠方法

這是我最喜歡的在 Java 中影響 Singleton 模式的方法之一,因為 Singleton 實例是靜態(tài)的,并且最后一個變量在類首次加載到內存時初始化,因此實例的創(chuàng)建本質上是線程安全的。

/**
* 單例模式示例與靜態(tài)工廠方法
*/
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;
    }
}

你可以調用 Singleton.getSingleton() 來獲取此類的訪問權限。

2) 枚舉單例自行處理序列化

傳統(tǒng)單例的另一個問題是,一旦實現(xiàn)可序列化接口,它們就不再是 Singleton, 因為 readObject() 方法總是返回一個新實例, 就像 Java 中的構造函數(shù)一樣。通過使用 readResolve() 方法, 通過在以下示例中替換 Singeton 來避免這種情況:

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

如果 Singleton 類保持內部狀態(tài), 這將變得更加復雜, 因為你需要標記為 transient(不被序列化),但使用枚舉單例, 序列化由 JVM 進行。

3) 創(chuàng)建枚舉實例是線程安全的

如第 1 點所述,因為 Enum 實例的創(chuàng)建在默認情況下是線程安全的, 你無需擔心是否要做雙重檢查鎖定。

總之, 在保證序列化和線程安全的情況下,使用兩行代碼枚舉單例模式是在 Java 5 以后的世界中創(chuàng)建 Singleton 的最佳方式。你仍然可以使用其他流行的方法, 如你覺得更好, 歡迎討論。

7. 編寫 Java 程序時, 如何在 Java 中創(chuàng)建死鎖并修復它?

經(jīng)典但核心Java面試問題之一。

如果你沒有參與過多線程并發(fā) Java 應用程序的編碼,你可能會失敗。

(視頻教程推薦:java課程

如何避免 Java 線程死鎖?

如何避免 Java 中的死鎖?是 Java 面試的熱門問題之一, 也是多線程的編程中的重口味之一, 主要在招高級程序員時容易被問到, 且有很多后續(xù)問題。盡管問題看起來非?;? 但大多數(shù) Java 開發(fā)人員一旦你開始深入, 就會陷入困境。

面試問題總是以“什么是死鎖?”開始

當兩個或多個線程在等待彼此釋放所需的資源(鎖定)并陷入無限等待即是死鎖。它僅在多任務或多線程的情況下發(fā)生。

如何檢測 Java 中的死鎖?

雖然這可以有很多答案, 但我的版本是首先我會看看代碼, 如果我看到一個嵌套的同步塊,或從一個同步的方法調用其他同步方法, 或試圖在不同的對象上獲取鎖, 如果開發(fā)人員不是非常小心,就很容易造成死鎖。

另一種方法是在運行應用程序時實際鎖定時找到它, 嘗試采取線程轉儲,在 Linux 中,你可以通過kill -3命令執(zhí)行此操作, 這將打印應用程序日志文件中所有線程的狀態(tài), 并且你可以看到哪個線程被鎖定在哪個線程對象上。

你可以使用 fastthread.io 網(wǎng)站等工具分析該線程轉儲, 這些工具允許你上載線程轉儲并對其進行分析。

另一種方法是使用 jConsole 或 VisualVM, 它將顯示哪些線程被鎖定以及哪些對象被鎖定。

如果你有興趣了解故障排除工具和分析線程轉儲的過程, 我建議你看看 Uriah Levy 在多元視覺(PluraIsight)上《分析 Java 線程轉儲》課程。旨在詳細了解 Java 線程轉儲, 并熟悉其他流行的高級故障排除工具。

()

編寫一個將導致死鎖的Java程序?

一旦你回答了前面的問題,他們可能會要求你編寫代碼,這將導致Java死鎖。

這是我的版本之一

/**
 * Java 程序通過強制循環(huán)等待來創(chuàng)建死鎖。
 *
 *
 */
public class DeadLockDemo {

    /*
     * 此方法請求兩個鎖,第一個字符串,然后整數(shù)
     */
     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");
            }
        }
    }


    /*
     * 此方法也請求相同的兩個鎖,但完全
     * 相反的順序,即首先整數(shù),然后字符串。
     * 如果一個線程持有字符串鎖,則這會產(chǎn)生潛在的死鎖
     * 和其他持有整數(shù)鎖,他們等待對方,永遠。
     */
     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");
            }
        }
    }
}

如果 method1() 和 method2() 都由兩個或多個線程調用,則存在死鎖的可能性, 因為如果線程 1 在執(zhí)行 method1() 時在 Sting 對象上獲取鎖, 線程 2 在執(zhí)行 method2() 時在 Integer 對象上獲取鎖, 等待彼此釋放 Integer 和 String 上的鎖以繼續(xù)進行一步, 但這永遠不會發(fā)生。

Do you know these 10 difficult Java interview questions?

此圖精確演示了我們的程序, 其中一個線程在一個對象上持有鎖, 并等待其他線程持有的其他對象鎖。

你可以看到, Thread1 需要 Thread2 持有的 Object2 上的鎖,而 Thread2 希望獲得 Thread1 持有的 Object1 上的鎖。由于沒有線程愿意放棄, 因此存在死鎖, Java 程序被卡住。

其理念是, 你應該知道使用常見并發(fā)模式的正確方法, 如果你不熟悉這些模式,那么 Jose Paumard 《應用于并發(fā)和多線程的常見 Java 模式》是學習的好起點。

如何避免Java中的死鎖?

現(xiàn)在面試官來到最后一部分, 在我看來, 最重要的部分之一; 如何修復代碼中的死鎖?或如何避免Java中的死鎖?

如果你仔細查看了上面的代碼,那么你可能已經(jīng)發(fā)現(xiàn)死鎖的真正原因不是多個線程, 而是它們請求鎖的方式, 如果你提供有序訪問, 則問題將得到解決。

下面是我的修復版本,它通過避免循環(huán)等待,而避免死鎖, 而不需要搶占, 這是需要死鎖的四個條件之一。

public class DeadLockFixed {

    /**
     * 兩種方法現(xiàn)在都以相同的順序請求鎖,首先采用整數(shù),然后是 String。
     * 你也可以做反向,例如,第一個字符串,然后整數(shù),
     * 只要兩種方法都請求鎖定,兩者都能解決問題
     * 順序一致。
     */
    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");
            }
        }
    }
}

現(xiàn)在沒有任何死鎖,因為兩種方法都按相同的順序訪問 Integer 和 String 類文本上的鎖。因此,如果線程 A 在 Integer 對象上獲取鎖, 則線程 B 不會繼續(xù), 直到線程 A 釋放 Integer 鎖, 即使線程 B 持有 String 鎖, 線程 A 也不會被阻止, 因為現(xiàn)在線程 B 不會期望線程 A 釋放 Integer 鎖以繼續(xù)。(實用詳盡的Java面試題大全,可以在Java知音公眾號回復“面試題聚合”)

8. 如果你的Serializable類包含一個不可序列化的成員,會發(fā)生什么?你是如何解決的?

任何序列化該類的嘗試都會因NotSerializableException而失敗,但這可以通過在 Java中 為 static 設置瞬態(tài)(trancient)變量來輕松解決。

Java 序列化相關的常見問題

Java 序列化是一個重要概念, 但它很少用作持久性解決方案, 開發(fā)人員大多忽略了 Java 序列化 API。根據(jù)我的經(jīng)驗, Java 序列化在任何 Java核心內容面試中都是一個相當重要的話題, 在幾乎所有的網(wǎng)面試中, 我都遇到過一兩個 Java 序列化問題, 我看過一次面試, 在問幾個關于序列化的問題之后候選人開始感到不自在, 因為缺乏這方面的經(jīng)驗。

他們不知道如何在 Java 中序列化對象, 或者他們不熟悉任何 Java 示例來解釋序列化, 忘記了諸如序列化在 Java 中如何工作, 什么是標記接口, 標記接口的目的是什么, 瞬態(tài)變量和可變變量之間的差異, 可序列化接口具有多少種方法, 在 Java 中,Serializable 和 Externalizable 有什么區(qū)別, 或者在引入注解之后, 為什么不用 @Serializable 注解或替換 Serializalbe 接口。

Do you know these 10 difficult Java interview questions?

在本文中,我們將從初學者和高級別進行提問, 這對新手和具有多年 Java 開發(fā)經(jīng)驗的高級開發(fā)人員同樣有益。

關于Java序列化的10個面試問題

大多數(shù)商業(yè)項目使用數(shù)據(jù)庫或內存映射文件或只是普通文件, 來滿足持久性要求, 只有很少的項目依賴于 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覆蓋靜態(tài)方法嗎?如果我在子類中創(chuàng)建相同的方法是編譯時錯誤?

不,你不能在Java中覆蓋靜態(tài)方法,但在子類中聲明一個完全相同的方法不是編譯時錯誤,這稱為隱藏在Java中的方法。

你不能覆蓋Java中的靜態(tài)方法,因為方法覆蓋基于運行時的動態(tài)綁定,靜態(tài)方法在編譯時使用靜態(tài)綁定進行綁定。雖然可以在子類中聲明一個具有相同名稱和方法簽名的方法,看起來可以在Java中覆蓋靜態(tài)方法,但實際上這是方法隱藏。Java不會在運行時解析方法調用,并且根據(jù)用于調用靜態(tài)方法的 Object 類型,將調用相應的方法。這意味著如果你使用父類的類型來調用靜態(tài)方法,那么原始靜態(tài)將從父類中調用,另一方面如果你使用子類的類型來調用靜態(tài)方法,則會調用來自子類的方法。簡而言之,你無法在Java中覆蓋靜態(tài)方法。如果你使用像Eclipse或Netbeans這樣的Java IDE,它們將顯示警告靜態(tài)方法應該使用類名而不是使用對象來調用,因為靜態(tài)方法不能在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");
    }
}

輸出:

Static method from parent class

此輸出確認你無法覆蓋Java中的靜態(tài)方法,并且靜態(tài)方法基于類型信息而不是基于Object進行綁定。如果要覆蓋靜態(tài)mehtod,則會調用子類或 ColorScreen 中的方法。這一切都在討論中我們可以覆蓋Java中的靜態(tài)方法。我們已經(jīng)確認沒有,我們不能覆蓋靜態(tài)方法,我們只能在Java中隱藏靜態(tài)方法。創(chuàng)建具有相同名稱和mehtod簽名的靜態(tài)方法稱為Java隱藏方法。IDE將顯示警告:"靜態(tài)方法應該使用類名而不是使用對象來調用", 因為靜態(tài)方法不能在Java中重寫。

這些是我的核心Java面試問題和答案的清單。對于有經(jīng)驗的程序員來說,一些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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

See all articles