Java little knowledge points: Object problems and various little knowledge points

Summarize the little knowledge points written before

Table of contents

Several questions about Object o = new Object()

1. The process of object creation

Main knowledge points: semi-initialized state during object creation

1. Take the following code as an example to see the process of creating an Object object

Object o = new Object();

2. The corresponding bytecode can be obtained through the jclasslib plug-in in the idea
jclasslib plugin
2.1. According to jclasslib, the bytecode information of the above code running is obtained as follows
Object object creation process bytecode
3. Analyze the creation process of the object through the bytecode information

  1. First of all, according to the first line of bytecode, it can be roughly analyzed that this is a new object, which corresponds to the java.lang.Object object. It can be roughly concluded that this line is to apply for a piece of memory to store the new object. At this time, the members in the object A variable is a default initial value .
  2. Then look at the third line of bytecode, which literally means to call the init method of java.lang.Object, here is to call the constructor of the object to initialize, after initialization, the member variables in the object are normal assignments .
  3. The fourth line of bytecode means to associate the variable o with the object .

2. Do DCL singletons need to be modified with volatile?

Main knowledge points: instruction reordering problem

1. Relevant knowledge points

  • volatile : Modification represents visibility between threads, while prohibiting instruction reordering
  • Instruction reordering : It is when the CPU acquires memory and executes instructions at the same time while waiting. The order of execution during the period becomes out of order, which is also due to the increase in efficiency of the CPU. It is like cooking and doing other things at the same time.
  • Singleton : A certain class can only create one new object in memory
  • DCL : Double check lock double check lock

2. DCL singleton code

public class DCL {
    
    

    private static volatile DCL INSTANCE;

    private DCL() {
    
    }

    public static DCL getInstance() {
    
    
        if (INSTANCE == null) {
    
    
            synchronized (DCL.class) {
    
    
                if (INSTANCE == null) {
    
    
                    try {
    
    
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
    
    
                        throw new RuntimeException(e);
                    }
                    INSTANCE = new DCL();
                }
            }
        }
        return INSTANCE;
    }

}

3. Analysis process

  1. From the problem of object creation process , we can know that when the first line of instructions executes semi-initialization, if the instructions on the 3rd and 4th lines are reordered ! ! !
  2. At this time, INSTANCE is only half-new, and the constructor has not yet been executed for initialization. What the second thread gets is a half-initialized object .
  3. At this time, the member variables in the object have not been assigned corresponding values, and data consistency cannot be guaranteed .
  4. Conclusion: If you want to ensure data consistency , you need to add it. You don’t need to ensure data consistency.

3. The storage layout of objects in memory

Main knowledge points: layout of objects and arrays in memory

1. To view the layout, you need to introduce the corresponding dependency package, which is jol-cord
JOL: Java Object Layer

<dependency>
    <groupId>org.openjdk.jol</groupId>
    <artifactId>jol-core</artifactId>
    <version>0.9</version>
</dependency>

2. The memory layout of common objects

Object o = new Object();
System.out.println(ClassLayout.parseInstance(o).toPrintable());

/** 运行结果
java.lang.Object object internals:
 OFFSET  SIZE   TYPE DESCRIPTION                               VALUE
      0     4        (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4        (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4        (object header)                           e5 01 00 f8 (11100101 00000001 00000000 11111000) (-134217243)
     12     4        (loss due to the next object alignment)
Instance size: 16 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
*/

3. Memory layout of array objects

Object[] os = new Object[1];
System.out.println(ClassLayout.parseInstance(os).toPrintable());

/** 运行结果
[Ljava.lang.Object; object internals:
 OFFSET  SIZE               TYPE DESCRIPTION                               VALUE
      0     4                    (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
      4     4                    (object header)                           00 00 00 00 (00000000 00000000 00000000 00000000) (0)
      8     4                    (object header)                           f5 22 00 f8 (11110101 00100010 00000000 11111000) (-134208779)
     12     4                    (object header)                           01 00 00 00 (00000001 00000000 00000000 00000000) (1)
     16     4   java.lang.Object Object;.<elements>                        N/A
     20     4                    (loss due to the next object alignment)
Instance size: 24 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
*/

4. Layout analysis

common object

  • The 12 bytes in the first three parts are object headers, which are markword, class pointer, and instance data
  • The 4 bytes after the 12th byte are the padding of the next object
  • So Object o = new Object() occupies 16 bytes in memory

array object

  • Compared with ordinary objects, the object header has a 4-byte array length and 4-byte elements

4. What does the object header specifically include?

Main knowledge points: markword, klasspointer

MarkWord

  • Mainly stores the runtime data of the object itself
  • Lock information, GC information, Identity hashcode
  • Test method: Add a lock to the object, and you can see that the VALUE in the memory layout object header has changed
synchronized (o) {
    
    
    System.out.println(ClassLayout.parseInstance(o).toPrintable());
}

/** 运行结果
java.lang.Object object internals:
 OFFSET  SIZE   TYPE DESCRIPTION                               VALUE
      0     4        (object header)                           88 a9 20 09 (10001000 10101001 00100000 00001001) (153135496)
      4     4        (object header)                           00 70 00 00 (00000000 01110000 00000000 00000000) (28672)
      8     4        (object header)                           e5 01 00 f8 (11100101 00000001 00000000 11111000) (-134217243)
     12     4        (loss due to the next object alignment)
Instance size: 16 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
*/

ClassPointer

  • The type pointer is the pointer of the object to the class metadata. Through this pointer, it is known which class the object is an instance of.
  • The object pointer is sometimes 4 bytes, sometimes 8 bytes, mainly because jvm starts compression + UserCompressedClassPointers by default, compressing 64 bits into 4 bytes
  • Expansion: When the memory exceeds 32G, it will expand to 8 bytes, and the compression will no longer work
    • The addressing limit of KlassPointer is 4byte * 8 byte = 32bit, which is 2 to the power of 32 memory unit addresses. The length of each object must also be an integer multiple of 8. When the memory address is greater than 32G, it cannot be searched, so the compression fails

Five, how to locate the object

Main knowledge points: direct and indirect addressing

Indirect (handle method)

  • Points to a set of pointers, an instance data pointer points to the real object in the heap, and a type pointer points to the class in the method area
  • Advantages: It is convenient for GC, and the variables pointed to by GC do not need to be changed when copying
  • Disadvantages: not very efficient

direct pointer

  • Directly point to the type data pointer in the heap, and the type data pointer points to the class in the method area
  • Advantages: direct search for high efficiency
  • Disadvantage: Every time the variable is changed, the variable pointed to needs to be changed

6. How to allocate objects

Main knowledge points: Online -> Thread Local -> Eden -> Old

allocation process

  • When creating a new object, first judge whether it can be placed on the stack, and it will be over as soon as the stack is popped (pop)
    • If the stack size is sufficient and there is no escape, it can be allocated to the stack. When recycling, GC does not need to intervene, and the efficiency is high.
  • Cannot be placed on the stack, and then judge whether it is very large, if it is very large, it will be directly placed on the old generation, and the object will be recycled after Full GC and Major GC
  • If it is not large, put it in the thread local buffer (TLAB), and put it in the Eden area if it cannot fit
    • TLAB: Thread local allocation buffer, each thread has an extra small space exclusively in the Eden area, and it will be placed in this place first, and it will be placed in the Eden area if it cannot be placed
  • After the Eden area is cleared by a GC, it will end. If it is not cleared, it will enter the Survive area, and then go through the GC. If it is old enough, it will enter the Eden area. If it is not enough, it will enter another Survive area cycle.

little knowledge

1. The difference between String and StringBuffer

  • String
    • The String object is immutable. The value change just creates a new object. The value exists in the constant pool and will not be destroyed if not used.
    • The String class is final modified and cannot be inherited
  • StringBuffer
    • The StringBuffer object is mutable and is mainly created according to the construction method. The object exists in the stack area and will be destroyed if it is not used.

2. The difference between int and Integer

  • Integer is the wrapper class of int, and int is the basic type of java
  • The default value of Integer is null, and the default value of int is 0
  • Integer points to an object, and int stores data values ​​directly (Java will cache values ​​from -128 to 127)

3. The difference between Array and ArrayList

  • Array can contain primitive types and object types, ArrayList can only contain object types
  • The size of Array is fixed, and the size of ArrayList can be changed dynamically
  • ArrayList provides more methods and features

4. What is pass by value and pass by reference?

  • Passing by value: When the method is called, the actual parameter will pass a copy of itself to the formal parameter, and the modification of the parameter in the method will not affect the actual parameter
  • Pass by reference: When the method is called, the actual parameter passes its address to the formal parameter. In the method, the change of the parameter is the actual operation of the actual parameter.
  • Primitive types are passed by value, reference types are passed by reference

5. What are the data types supported by Java, what are automatic unboxing and automatic boxing

  • byte、short、int、long、double、float、boolean、char
  • Automatic unboxing: assign a wrapper class object to the data of the basic type of the class
  • Autoboxing: assigning a basic type of data to a wrapper object
  • Both can greatly simplify the conversion process between basic type variables and wrapper class objects

6. Why does 4.0-3.6=0.4000000001 appear?

  • Computers use binary, but floating-point numbers cannot be accurate using binary. The computer shows us decimal or we input decimal to the computer for processing, which requires constant conversion between binary and decimal

7. A brief introduction to the new features of Java8

  • Lambda expressions
    • Parameter list -> implement logic
  • functional interface
    • An interface containing only one abstract method, and an anonymous implementation class can be written using Lambda expressions
  • method reference/constructor reference
    • method reference
      • object::instance method name
      • class::static method-name
      • class::instance method-name
  • constructor reference
    • ClassName::new
  • Stream API
    • The key abstraction for working with collections, providing an efficient and easy-to-use way of working with data
    • Collection is a static memory data structure, which is mainly oriented to memory and stored in memory. Stream is related to calculation, mainly oriented to CPU, and the calculation is realized through CPU
    • Steps
      • Create Stream: data source acquisition stream (array, collection)
      • Intermediate operation: process the data of the data source
      • Termination operation: perform intermediate operations and produce results
    • Note: Stream will not store elements, will not change the source object, returns a new result Stream, lazy operation, and will only be executed when the result is needed
  • Optional class
    • Container class, which can save the value of type T, which means that this value exists, or only save null, which means that this value does not exist, and can avoid null pointers

8. The difference between == and equals

  • == is to judge whether it points to the same memory space, and equals is to judge whether the value of the pointed memory space is the same
  • == is to compare memory addresses, and equals is to compare string contents
  • == refers to whether the usage is the same, equals refers to whether the value is the same

9. If the Object does not rewrite the hashCode, how to calculate the hashCode

  • If not rewritten, the local method is used, and the memory address of the current object is returned

10. Why rewrite equals but also rewrite hashcode

  • Because it must be guaranteed that the rewritten equals method recognizes that the same two objects have the same hashcode
  • The principle of rewriting the hashcode method is to ensure that the equals method recognizes that the two objects that are the same have the same hashcode

11. If a class is not rewritten, how does its equals method compare

  • The comparison is the address of the object pointed to by the variable of the reference type, which is the same as ==

12. How to use the final keyword in Java

  • Modified class, method, local variable, member variable
  • Classes cannot be inherited, methods cannot be overridden, and variables cannot be modified after assignment

13. Introduce volatile

  • A keyword that guarantees visibility and prohibits instruction reordering
  • Variables modified by volatile are stored in the main memory. When modified, the main memory will be modified at the same time. When reading, the variable is directly read from the main memory.

14. About Synchronized and Lock

  • synchronized can be added to methods or code blocks, and lock needs to explicitly specify the start and end positions
  • synchronized is hosted and executed in jvm, and lock is a control lock code written in Java
  • synchronized is a pessimistic lock, lock is an optimistic lock
  • synchronized is a keyword, lock is an interface

15. What does Synchronized modify static methods and modify member methods to lock?

  • Static method: lock the object
  • Member method: lock the instance object

16. The meaning of method overriding and method overloading

  • Method coverage: overwrite the previous method (Override)
  • Method overloading: the same method name, but the passed parameters are different

17. How to obtain object private field value through reflection

  • getDeclaredField gets the field, setAccessible(true) sets the access permission

18. Can an inner class refer to the members of its containing class? What are the restrictions?

  • Inner Class Access Rules
    • The inner class can directly access the members of the outer class, including private, because the inner class holds a reference to the outer class (outer class name.this)
    • The outer class needs to create an object to access the inner class
  • static inner class
    • Modified with static, it can only access static member variables or methods in external classes in terms of access restrictions
  • member inner class
    • Ordinary inner classes can unconditionally access all member properties and member methods of outer classes (including private and static)
    • When the internal and external classes have variables or methods with the same name, the external ones will be hidden. If you need to access the external ones, you need to access the .this. member of the external class
  • local inner class
    • Defined in the method of the external class, you can directly access all members of the external class, but you cannot access local variables casually, and local variables can be accessed only after they are modified by final
  • anonymous inner class
    • Inner classes must either inherit from a class or implement an interface

19. What is a paradigm

  • Is a writing specification, compile-time type safety detection mechanism

20. Explain the class loading mechanism, the parental delegation model, and what are the benefits

  • class loading mechanism
    • Load the data describing the class from the class file to the memory, and verify, convert, parse and initialize the data, and finally form a Java type that can be directly used by the virtual machine
  • Parental Delegation Model
    • When receiving a class loading request, first entrust the loading task to the parent class loader, and recurse in turn. If the parent class loader completes the class loading task, it will return successfully. When the parent class cannot complete the loading, it will load it by itself.
  • benefit
    • No matter which class loader wants to load this class, it is ultimately delegated to the Bootstrap ClassLoader at the top of the model for loading, so it is the same class in different environments

21. The static keyword means whether it can override private or static method

  • static: The content modified by the static keyword is static
    • Methods, variables: can be accessed without creating an object
    • Code block: the code that is executed first when it is created, and performs some complex initialization work
  • Private and static methods cannot be overridden. Method overriding is run-time binding, and static is compile-time static binding. Private other classes cannot access this method

22. The difference between classes and objects

  • A class is a template for an object, and an object is an instance of a class. Classes can only be used through objects, and classes should be generated first during development, and then objects should be generated. Classes cannot be used directly, objects can be used directly.

23. Threads and processes

  • A process is the smallest unit of resource allocation, a thread is the smallest unit of program execution, and the smallest unit of resource scheduling
  • A process has an independent address space, and a thread is the data in a shared process
  • A process can have multiple threads, a thread has only one process
  • Different processes need to communicate to achieve synchronization, and different threads need to cooperate and synchronize
  • Popular: threads are sons, processes are fathers, a father can have multiple sons, and a son has only one father

Guess you like

Origin blog.csdn.net/baidu_40468340/article/details/128465625