亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java JavaInterview questions java gc interview questions and answers (questions 1~5)

java gc interview questions and answers (questions 1~5)

Nov 16, 2019 pm 04:06 PM
java

java gc interview questions and answers (questions 1~5)

1. Since there is a GC mechanism, why are there still memory leaks?

Theoretically, Java has a garbage collection mechanism (GC ) There will be no memory leak problem (this is also an important reason why Java is widely used in server-side programming). However, in actual development, there may be useless but reachable objects that cannot be recycled by GC, thus causing memory leaks.

For example, the objects in hibernate's Session (first-level cache) are persistent, and the garbage collector will not recycle these objects. However, there may be useless garbage objects in these objects. If they are not closed in time (close ) or flushing the first-level cache may cause memory leaks.

The code in the following example will also cause a memory leak.

import java.util.Arrays;
import java.util.EmptyStackException;
public class MyStack<T> {
    private T[] elements;
    private int size = 0;
    private static final int INIT_CAPACITY = 16;
    public MyStack() {
        elements = (T[]) new Object[INIT_CAPACITY];
    }
    public void push(T elem) {
        ensureCapacity();
        elements[size++] = elem;
    }
    public T pop() {
        if (size == 0) throw new EmptyStackException();
        return elements[--size];
    }
    private void ensureCapacity() {
        if (elements.length == size) {
            elements = Arrays.copyOf(elements,2 * size + 1);
        }
    }
}

The above code implements a stack (first in, last out (FILO)) structure. At first glance, there seems to be no obvious problem. It can even pass various unit tests you write.

However, the pop method has a memory leak problem. When we use the pop method to pop an object in the stack, the object will not be treated as garbage collection, even if the program using the stack no longer references these objects. , because obsolete references to these objects are maintained internally on the stack. In languages ??that support garbage collection, memory leaks are very hidden. This kind of memory leak is actually unconscious object retention.

If an object reference is retained unconsciously, the garbage collector will not process this object, nor will it process other objects referenced by this object. Even if there are only a few such objects, it may As a result, many objects are excluded from garbage collection, which has a significant impact on performance. In extreme cases, Disk Paging (exchanging data between physical memory and the virtual memory of the hard disk) may be caused, or even an OutOfMemoryError may be caused.

2. Why is there a GC mechanism in Java?

·Safety considerations;--for security.

·Reduce memory leaks;--erase memory leak in some degree.

·Reduce programmer work quantity. --Programmers dont worry about memory releasing.

3. Which memory needs to be recycled for Java's GC?

When memory is running, the JVM will have a runtime data area to manage memory.

It mainly includes 5 parts:

Program CounterRegister;

Virtual Machine Stack (VM Stack);

Native Method Stack;

Method Area;

Heap.

The program counter, virtual machine stack, and local method stack are the private memory spaces of each thread. They are born and die with the thread. For example, how much memory is allocated in each stack frame in the stack is basically known when the class structure is determined. Therefore, the memory allocation and recycling of these three areas are determined, and there is no need to consider the issue of memory recycling.

But the method area and the heap are different. Multiple implementation classes of an interface may require different memory. We will only know which objects will be created during the running of the program. The allocation and recycling of this part of memory They are all dynamic, and the GC mainly focuses on this part of memory. All in all, the memory that GC mainly reclaims is the method area and heap in the JVM.

4. When does Java's GC collect garbage?

In interviews, we often encounter this question (in fact, the author has also encountered it): How to judge that an object is dead?

An easy answer to think of is: add a reference counter to an object. Whenever there is a reference to it, the counter value is incremented by 1; when the reference expires, the counter value is decremented by 1. When the counter value is 0, the object will no longer be used and is judged to be dead. Isn't it simple and intuitive?

However, it is a pity. This approach is wrong! Why is it wrong? In fact, using reference counting is indeed a good solution in most cases, and there are many cases in actual applications, but it cannot solve the problem of circular references between objects.

For example, there is a field in object A that points to object B, and there is a field in object B that points to object A. In fact, both of them are no longer used, but the value of the counter can never be 0. , it will not be recycled, and then a memory leak occurs.

What should be the correct approach?

In languages ??such as Java and C#, the more mainstream method of determining the death of an object is: Reachability Analysis. All generated objects are called "GC Roots" "The subtree of the root.

Start from GC Roots and search downward. The path traveled by the search is called the reference chain. When an object has no reference chain to reach GC Roots, it is said that the object is unreachable. (non-referenceable), that is, it can be recycled by GC.

Whether it is a reference counter or reachability analysis, determining whether an object is alive is related to references! So, how to define a reference to an object?

我們希望給出這樣一類描述:當內(nèi)存空間還夠時,能夠保存在內(nèi)存中;如果進行了垃圾回收之后內(nèi)存空間仍舊非常緊張,則可以拋棄這些對象。所以根據(jù)不同的需求,給出如下四種引用,根據(jù)引用類型的不同,GC回收時也會有不同的操作:

強引用(Strong Reference):Object obj=new Object();只要強引用還存在,GC永遠不會回收掉被引用的對象。

軟引用(Soft Reference):描述一些還有用但非必需的對象。在系統(tǒng)將會發(fā)生內(nèi)存溢出之前,會把這些對象列入回收范圍進行二次回收(即系統(tǒng)將會發(fā)生內(nèi)存溢出了,才會對他們進行回收)

弱引用(Weak Reference):程度比軟引用還要弱一些。這些對象只能生存到下次GC之前。當GC工作時,無論內(nèi)存是否足夠都會將其回收(即只要進行GC,就會對他們進行回收。)

虛引用(Phantom Reference):一個對象是否存在虛引用,完全不會對其生存時間構(gòu)成影響。關(guān)于方法區(qū)中需要回收的是一些廢棄的常量和無用的類。

1.廢棄的常量的回收。這里看引用計數(shù)就可以了。沒有對象引用該常量就可以放心的回收了。

2.無用的類的回收。什么是無用的類呢?

A.該類所有的實例都已經(jīng)被回收。也就是Java堆中不存在該類的任何實例;

B加載該類的ClassLoader已經(jīng)被回收;

C.該類對應的java.lang.Class對象沒有任何地方被引用,無法在任何地方通過反射訪問該類的方法。

總而言之:對于堆中的對象,主要用可達性分析判斷一個對象是否還存在引用,如果該對象沒有任何引用就應該被回收。而根據(jù)我們實際對引用的不同需求,又分成了4種引用,每種引用的回收機制也是不同的。

對于方法區(qū)中的常量和類,當一個常量沒有任何對象引用它,它就可以被回收了。而對于類,如果可以判定它為無用類,就可以被回收了。

5、通過10個示例來初步認識Java8中的lambda表達式

用lambda表達式實現(xiàn)Runnable

// Java 8 之前:
new Thread(new Runnable(){
    @Override
    public void run(){
        System.out.println("Before Java8, too much code for too little to do");
    }}).start();
    //Java 8 方式:
    new Thread(()->System.out.println("In Java8, Lambda expression rocks !!")).start();

輸出:

too much code,for too little to do
Lambda expression rocks!!

這個例子向我們展示了Java 8 lambda表達式的語法。你可以使用lambda寫出如下代碼:

(params) -> expression (params) -> statement
(params) -> { statements }

例如,如果你的方法不對參數(shù)進行修改、重寫,只是在控制臺打印點東西的話,那么可以這樣寫:

() -> System.out.println("Hello Lambda Expressions");

如果你的方法接收兩個參數(shù),那么可以寫成如下這樣:

(int even, int odd) -> even + odd

順便提一句,通常都會把lambda表達式內(nèi)部變量的名字起得短一些。這樣能使代碼更簡短,放在同一行。所以,在上述代碼中,變量名選用a、b或者x、y會比even、odd要好。

使用Java 8 lambda表達式進行事件處理

如果你用過Swing API編程,你就會記得怎樣寫事件監(jiān)聽代碼。這又是一個舊版本簡單匿名類的經(jīng)典用例,但現(xiàn)在可以不這樣了。你可以用lambda表達式寫出更好的事件監(jiān)聽代碼,如下所示:

// Java 8 之前:
JButton show = new JButton("Show"); show.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Event handling without lambda expression is boring");
    }
});
// Java 8 方式:
show.addActionListener((e) -> {
    System.out.println("Light, Camera, Action !! Lambda expressions Rocks");
});

使用Java 8 lambda表達式進行事件處理 使用lambda表達式對列表進行迭代

如果你使過幾年Java,你就知道針對集合類,最常見的操作就是進行迭代,并將業(yè)務邏輯應用于各個元素,例如處理訂單、交易和事件的列表。

由于Java是命令式語言,Java 8之前的所有循環(huán)代碼都是順序的,即可以對其元素進行并行化處理。如果你想做并行過濾,就需要自己寫代碼,這并不是那么容易。

通過引入lambda表達式和默認方法,將做什么和怎么做的問題分開了,這意味著Java集合現(xiàn)在知道怎樣做迭代,并可以在API層面對集合元素進行并行處理。

下面的例子里,我將介紹如何在使用lambda或不使用lambda表達式的情況下迭代列表。你可以看到列表現(xiàn)在有了一個forEach()方法,它可以迭代所有對象,并將你的lambda代碼應用在其中。

// Java 8 之前:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API","Date and Time API");
for (String feature : features) {
    System.out.println(feature);
}
// Java 8 之后:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API","Date and Time API");
features.forEach(n -> System.out.println(n));
// 使用 Java 8 的方法引用更方便,方法引用由::雙冒號操作符標示,
// 看起來像 C++的作用域解析運算符
features.forEach(System.out::println);

輸出:

Lambdas Default Method Stream API
Date and Time API

列表循環(huán)的最后一個例子展示了如何在Java 8中使用方法引用(method reference)。你可以看到C++里面的雙冒號、范圍解析操作符現(xiàn)在在Java 8中用來表示方法引用。

使用lambda表達式和函數(shù)式接口Predicate

除了在語言層面支持函數(shù)式編程風格,Java 8也添加了一個包,叫做java.util.function。它包含了很多類,用來支持Java的函數(shù)式編程。其中一個便是Predicate,使用java.util.function.Predicate函數(shù)式接口以及l(fā)ambda表達式,可以向API方法添加邏輯,用更少的代碼支持更多的動態(tài)行為。下面是Java 8 Predicate的例子,展示了過濾集合數(shù)據(jù)的多種常用方法。Predicate接口非常適用于做過濾。

public static void main(String[]args){
    List languages=Arrays.asList("Java", "Scala","C++", "Haskell", "Lisp");
    System.out.println("Languages which starts with J :");
    filter(languages, (str)->str.startsWith("J"));
    System.out.println("Languages which ends with a ");
    filter(languages, (str)->str.endsWith("a"));
    System.out.println("Print all languages :");
    filter(languages, (str)->true);
    System.out.println("Print no language : ");
    filter(languages, (str)->false);
    System.out.println("Print language whose length greater than 4:");
    filter(languages, (str)->str.length()>4);
}
public static void filter(List names, Predicate condition){
    for(String name:names){
        if(condition.test(name)){
            System.out.println(name+" ");
        }
    }
}
// filter 更好的辦法--filter 方法改進
public static void filter(List names, Predicate condition) {
    names.stream().filter((name)->(condition.test(name))).forEach((name)->
{System.out.println(name + " ");
    });
}

可以看到,Stream API的過濾方法也接受一個Predicate,這意味著可以將我們定制的filter()方法替換成寫在里面的內(nèi)聯(lián)代碼,這就是lambda表達式的魔力。另外,Predicate接口也允許進行多重條件的測試。

The above is the detailed content of java gc interview questions and answers (questions 1~5). 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
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

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.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

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

See all articles