[java] basic knowledge (2)

wait/sleep difference

1. from a different class

wait =>object

sleep =>thread

2. About the release of the lock

wait will release the lock

sleep will not release

3. The scope of application is different

wait: must be in a synchronous code block

sleep: can be anywhere

4. Do you need to catch exceptions

wait does not need to catch exceptions

sleep needs to catch exceptions

The difference between synchronized and lock 

1. Synchronized is a built-in java keyword, lock is a Java class

2. Synchronized cannot judge the state of acquiring the lock, but lock can determine whether to acquire the lock

3.synchronized will automatically release the lock. The lock must be released manually, if it is not released, it will deadlock

4. Synchronized thread 1 (obtain lock, block), thread 2 (wait, silly, etc.); lock lock may not wait

5. Synchronized reentrant lock, can not be interrupted, unfair; lock, reentrant lock, can judge the lock, unfair (you can set it yourself)

6. Synchronized is suitable for a small amount of code synchronization; lock is suitable for a large number of synchronization codes

 bottom layer of hashset

The bottom layer of HashSet is HashMap

players

JUC is the abbreviation of java.util.concurrent package, added in Java5.0, the purpose is to better support high concurrent tasks. Let developers reduce the problems of race conditions and deadlocks when doing multi-threaded programming! 

  • Lock framework and Tools class
  • Collections: concurrent collections
  • Atomic: atomic class
  • Executors: thread pool

Persistence

Persistence is the mechanism for converting program data between persistent and transient states. In layman's terms, transient data (such as data in memory, which cannot be stored permanently) is persisted to persistent data (such as persisting to the database, which can be stored for a long time). 

The difference between optimistic locking and pessimistic locking

One: Optimistic Lock (Optimistic Lock)

 Every time you get data, you don't worry that the data will be modified, so you don't lock it every time you get data.

 However, when updating data, it is necessary to determine whether the data has been modified by others. If the data has been modified by other threads, the data will not be updated.

 If the data has not been modified by other threads, the data is updated. Since the data is not locked, the data can be read and written by other threads during this period.

Two: Pessimistic Lock (Pessimistic Lock)

 Every time you get data, you will worry that the data will be modified, so you will lock it every time you get data.

 Make sure that the data is not modified by others during your own use, and unlock the data after use.

 Since the data will be locked, the data will be read and written and other threads will wait during the period.

Three: Applicable occasions

 Optimistic lock: more suitable for occasions where read operations are frequent.

     If there are a large number of write operations, the possibility of data conflicts will increase. In order to ensure data consistency,

     The application layer needs to constantly re-acquire data, which will increase a large number of query operations and reduce the throughput of the system.

 Pessimistic lock: It is more suitable for occasions where write operations are frequent.

     If there are a large number of read operations, each read will be locked, which will increase the overhead of a large number of locks and reduce the throughput of the system.

 Summary: Both types of locks have their own advantages. Frequent reads use optimistic locks, and frequent writes use pessimistic locks.

 CRUD

Crud refers to the acronym for the words Add (Create), Retrieve (Retrieve), Update (Update) and Delete (Delete) when doing calculation processing . CRUD is mainly used to describe the basic operating functions of the database or persistence layer in the software system.

java access modifier

  • default: default access modifier, visible within the same package
  • private: Visible within the same class, cannot modify the class
  • protected : Visible to classes and all subclasses in the same package, cannot modify classes
  • public: visible to all classes

The initialization order of the constructor, member variable initialization and static member variables?

Sequence: static member variables, member variables, constructors. Detailed sequence: parent static variable, parent static code block, subclass static variable, subclass static code block, parent non-static variable, parent non-static code block, parent constructor, subclass non-static variable , subclass non-static code block, subclass constructor. 

What are the similarities and differences between interface and abstract class?

Same point:

  1. Neither can be instantiated.
  2. The implementation class of the interface or the subclass of the abstract class needs to implement the corresponding method in the interface or abstract class before it can be instantiated.

difference:

  1. Interfaces can only have method definitions, not method implementations, while abstract classes can have method definitions and implementations.

  2. The keyword for implementing an interface is implements, and the keyword for inheriting an abstract class is extends. A class can implement multiple interfaces and can only inherit from one abstract class.

  3. When there is a logical hierarchy between the subclass and the parent class, it is recommended to use an abstract class, which is conducive to the accumulation of functions. When the function is not required and you want to support specific interaction behaviors between two or more objects with large differences, it is recommended to use the interface. The use of interfaces can reduce the coupling degree of the software system, which is convenient for future maintenance or adding and deleting methods.

The polymorphic mechanism provided by Java

Java provides two mechanisms for polymorphism, namely overloading and overriding.

  1. Overloading: Overloading means that there are multiple methods with the same name in the same class, but these methods have different parameters, and which method to call can be determined during compilation.
  2. Coverage: Coverage refers to the method of rewriting the base class by the derived class, using the base class to point to the instance object of its subclass, or the reference variable of the interface to point to the instance object of its implementation class, according to the reference variable pointed to during the runtime of the program call The specific instance object calls the method of the object that is running, that is, it needs to be at runtime to determine which method to call.

The difference between overloading and overriding

  1. Coverage is the relationship between the parent class and the child class, which is a vertical relationship; overloading is the relationship between methods in the same class, which is a horizontal relationship.
  2. Overriding can only create a relationship by a method or a pair of methods; overloading is a relationship between multiple methods.
  3. Overriding requires the same argument list; overloading requires a different argument list.
  4. In overriding, the body of the calling method is determined according to the type of the object, while the body of the method is selected correspondingly according to the actual parameter list and the formal parameter list when overloading.
  5. Overloaded methods can change the type of the return value, while overriding methods cannot change the type of the return value.

Will the finally code block appearing in the Java program be executed?

It will not be executed when the following conditions are encountered.

  1. When an exception occurs before the program enters the try statement block, it will end directly.
  2. When the program is forced to exit in the try block, such as using System.exit(0), the code in the finally block will not be executed.

In other cases, when the try/catch/finally statement is executed, the try block is executed first. When an exception occurs, the program ends after catch and finally are processed. When no exception occurs, after the code in finally is executed, The following code will continue to execute. It is worth noting that when there is a return in the try/catch statement block, the code in the finally statement block will be executed before the return. If there are return statements in the try/catch/finally block, the return statement in the finally block will override the return statement in the try/catch module.

What is the role of the keyword static in the Java language

There are two main functions of static:

  1. Allocate a single storage space for a specific data type or object regardless of the number of objects created.
  2. Make a method or attribute associated with a class instead of an object, that is, you can directly call a method or use an attribute of a class without creating an object.

Specifically, static can be divided into four usage methods:

  1. Modify member variables. Static variables decorated with the static keyword have only one copy in memory. As long as the class where the static variable is located is loaded, the static variable will be allocated space, which can be used with the methods of ''class.static variable'' and ''object.static variable''.
  2. Decorate member methods. Static modified methods can be called without creating an object. The this and super keywords cannot be used in the static method, and non-static methods cannot be called, and only the static member variables and static member methods of the class to which it belongs can be accessed.
  3. Decorate code blocks. The JVM will execute the static code block when loading the class. Static code blocks are often used to initialize static variables. A static code block will only be executed once.
  4. Modified inner class. The static inner class can be instantiated without relying on the outer class instance object. The static inner class cannot have the same name as the outer class, cannot access ordinary member variables, and can only access static members and static member methods in the outer class.

What is the difference between String and StringBuffer

String is used for string operations and is an immutable class. Once a String object is created, its value cannot be changed. StringBuffer is a mutable class, and its value can still be modified after the object is created. 

The difference between equality operator == and equals

==  compares references, and equals compares content.

  1. If the variable is a basic data type, ==  is used to compare whether its corresponding values ​​are equal. If the variable points to an object, ==  is used to compare whether two objects point to the same storage space.

  2. equals is one of the methods provided by the Object class. Every Java class inherits from the Object class, so every object has the equals method. The equals method defined in the Object class directly calls  the ==  comparison object. But by overriding the method, it is not to compare the reference but to compare the data content.

Why should String be designed as an invariant

  1. Space saving: String constants are stored in the JVM's string pool and can be shared by users.
  2. Improve efficiency: String will be shared by different threads and is thread-safe. Synchronization operations are not required in operations involving multiple threads.
  3. Security: String is often used for user names, passwords, file names, etc. Because it is immutable, it can prevent hackers from maliciously modifying it.

what is serialization

Serialization is the process of converting an object into a sequence of bytes to solve problems that arise when reading and writing to a stream of objects. Serialization can write the state of the object in the stream for network transmission, or save it in a file, database and other systems, and read the stream and reconstruct it into the same object when needed. 

Briefly describe the Class object in Java

Objects in java can be divided into instance objects and Class objects. Each class has a Class object, which contains information related to the class.

The method to get the Class object:

  • Class.forName("The fully qualified name of the class")
  • instance object.getClass()
  • classname.class

What is the Java reflection mechanism

The Java reflection mechanism means that during the running of the program, objects of any class can be constructed, member variables and member methods of any class can be obtained, class information of any object can be obtained, and properties and methods of any object can be called. The reflection mechanism enables Java to have the ability to dynamically obtain program information and dynamically call object methods. The reflection API can be called through the following classes.

  • Class class: available class attribute methods
  • Field class: get the member variables of the class
  • Method class: Get the method information of the class
  • Construct class: Obtain information such as the construction method of the class

brief comment

Java annotations are used to provide metadata for Java code. As metadata, annotations do not directly affect your code execution, but there are some types of annotations that can actually be used for this purpose.

It can be used to provide information to the compiler, to provide information to the software for related processing during the compilation phase, and to write corresponding codes and perform corresponding operations during runtime.

Meta annotations in brief

Meta-annotations can be understood as annotations of annotations, that is, used in annotations to achieve the desired function. It is specifically divided into:

  • @Retention: Indicates whether the annotation exists in the source code, or in the bytecode (class loading) or runtime (running in the JVM).
  • @Target: Indicates the scope of the annotation.
  • @Documented: Include the elements in the annotation into the Javadoc.
  • @Inherited: An annotation annotated by @Inherited modifies a parent class. If its subclass is not modified by other annotations, its subclass also inherits the annotations of the parent class.
  • @Repeatable: The annotation modified by this meta-annotation can act on an object multiple times at the same time, but each time the annotation can represent different meanings.

Briefly describe the classification of Java exceptions

Java exceptions are divided into Error (errors that the program cannot handle) and Exception (exceptions that the program itself can handle). Both classes inherit Throwable.

The common errors are StackOverFlowError, OutOfMemoryError and so on.

Exception can be divided into runtime exceptions and non-runtime exceptions. For runtime exceptions, you can use try catch to handle them, or you don't have to. For non-runtime exceptions, they must be handled. If they are not handled, the program cannot be compiled.

Briefly describe the difference between throw and throws

Throw is generally used inside the method body, and it is defined by the developer to actively throw an exception when there is a problem with the program statement.

throws is generally used in method declarations, representing a list of exceptions that may be thrown by the method.

Generics briefly

Generics, or "parameterized types", solve the problem of not being sure about the specific type of an object. Valid at compile time. In the process of using generics, the data type of the operation is specified as a parameter. This parameter type is called a generic class in a class, a generic interface in an interface, and a generic method in a method. 

Generic erasure in brief

The bytecode generated by the Java compiler does not contain generic information, and the generic type information will be erased during compilation. This process is called generic erasure. 

A Brief Introduction to Java Basic Data Types

  • byte: Occupies 1 byte, value range -128 ~ 127
  • short: Occupies 2 bytes, value range -2^15^ ~ 2^15^-1
  • int: Occupies 4 bytes, value range -2^31^ ~ 2^31^-1
  • long: occupies 8 bytes
  • float: occupies 4 bytes
  • double: occupies 8 bytes
  • char: occupies 2 bytes
  • boolean: The occupied size varies according to the implementation of the virtual machine 

A brief description of automatic boxing and unboxing

For Java basic data types, each corresponds to a wrapper class.

Boxing is to automatically convert basic data types to wrapper types, such as int->Integer

Unboxing is to automatically convert the wrapper type to a basic data type, such as Integer->int

Briefly describe the common methods of the Object class

  1. hashCode: The hash code calculated by the object. For map type or equals method. It is necessary to ensure that the same object calls this method multiple times and always returns the same integer value.
  2. equals: Determines whether two objects are consistent. It is necessary to ensure that the hashCode of the objects corresponding to the same equals method is also the same.
  3. toString: represent the object with a string
  4. clone: ​​deep copy an object

A brief introduction to inner classes and their functions

  • Member Inner Class: An inner class that is a member object. You can access the properties and methods of private and above external classes. When the outer class wants to access the properties or methods of the inner class, it must create an inner class object, and then access the properties or methods of the inner class through this object. External classes can also access private modified internal class attributes.
  • Local Inner Class: An inner class that exists within a method. Access rights are similar to local variables, and can only access final variables of external classes.
  • Anonymous inner class: can only be used once, has no class name, and can only access the final variables of the outer class.
  • Static Inner Class: Similar to static member variables of a class.

Briefly describe String/StringBuffer and StringBuilder

The String class uses a final-modified character array for string storage, so it is immutable. If you modify the String type object, you need to create a new object, and store the old characters and the newly added characters together.

StringBuilder is stored in a character array without final modification, so it is variable. But it's not thread safe.

StringBuffer, which is stored in a character array without final modification, can be understood as a thread-safe StringBuilder

Briefly describe the implementation of Java serialization and deserialization

Serialization: convert java objects into byte sequences, which can be transmitted through network objects.

Deserialization: convert byte sequence to java object.

Specific implementation: implement the Serializable interface, or implement the writeExternal() and readExternal() methods in the Externalizable interface.

A brief description of JAVA's List

List is an ordered queue, and there are two implementations in JAVA:

ArrayList is implemented using an array. It is a non-thread-safe list with variable capacity and fast random access. When the collection is expanded, a larger array will be created and the original array will be copied to the new array.

LinkedList is essentially a doubly linked list. Compared with ArrayList, insertion and deletion are faster, but random access to elements is slow. 

What are the basic data structures of thread safety in Java

HashTable: thread-safe version of hash table, low efficiency

ConcurrentHashMap: thread-safe version of hash table, high efficiency, used to replace HashTable

Vector: thread-safe version

Arraylist Stack: thread-safe stack

BlockingQueue and its subclasses: thread-safe queues 

A brief introduction to JAVA's Set 

Set is a collection, and this data structure does not allow elements to be repeated and out of order. JAVA has three implementations for Set:

HashSet is realized through HashMap, the Key of HashMap is the element stored in HashSet, and the Value system customizes an Object type constant named PRESENT. When judging whether the elements are the same, first compare the hashCode, and then use equals to compare the same, query O(1)

LinkedHashSet inherits from HashSet and is implemented through LinkedHashMap, using a doubly linked list to maintain the insertion order of elements.

TreeSet is implemented by TreeMap. The underlying data structure is a red-black tree. When adding elements to the collection, it is inserted into the appropriate position according to the comparison rules to ensure that the inserted collection is still in order. query O(logn)

Briefly describe HashMap of JAVA

Before JDK8, the underlying implementation was array + linked list, but in JDK8 it was changed to array + linked list/red-black tree. The main member variables include the table array for storing data, the number of elements size, and the load factor loadFactor. The data in the HashMap exists in the form of key-value pairs, and the hash value corresponding to the key is used to calculate the array subscript. If the hash values ​​of the two element keys are the same, a hash conflict will occur and they will be placed on the same linked list.

The table array records the data of the HashMap. Each subscript corresponds to a linked list. All hash conflict data will be stored in the same linked list. The Node/Entry node contains four member variables: key, value, next pointer and hash value. After JDK8, the linked list exceeds 8 and will be converted into a red-black tree.

If the current data/total data capacity > load factor, Hashmap will perform capacity expansion. The default initial capacity is 16, the expansion capacity must be a power of 2, the maximum capacity is 1<< 30, and the default load factor is 0.75.

Why is HashMap thread unsafe

In JDK1.7, HashMap uses the head insertion method to insert elements, so it will lead to a circular linked list under concurrent conditions, resulting in an infinite loop.

Although JDK1.8 uses the tail insertion method to solve this problem, the concurrent put operation will also cause the previous key to be overwritten by the latter key.

Since the HashMap has an expansion mechanism, there is also a situation where the B thread executes the get method after the A thread expands the capacity.

Briefly describe Java's TreeMap

TreeMap is a Map structure implemented by the red-black tree at the bottom layer. The bottom layer implementation is a balanced sorted binary tree. Since the insertion, deletion, and traversal time complexity of the red-black tree are O(logN), the performance is lower than that of the hash table. . However, the hash table cannot provide ordered output of key-value pairs, and the red-black tree can output orderly according to the size of the key value. 

What is the difference between Collectionand Collections

 

  1. Collection is a collection interface, which provides general interface methods for basic operations on collection objects, and all collections are its subclasses, such as List, Set, etc.
  2. Collections is a wrapper class that contains many static methods and cannot be instantiated, but is used as a tool class, such as the sorting method provided: Collections.sort(list); the reverse method provided: Collections.reverse(list).

What are the commonalities and differences between ArrayList, Vector and LinkedList

  1. ArrayList, Vector, and LinkedList are all scalable arrays, that is, arrays that can dynamically change their length.
  2. Both ArrayList and Vector are implemented based on the Object[] array that stores elements. They will open up a continuous space in memory for storage, and support subscript and index access. But when it comes to inserting elements, the elements in the container may need to be moved, and the insertion efficiency is low. When the storage elements exceed the initial capacity of the container, both ArrayList and Vector will expand.
  3. Vector is thread-safe and most of its methods are directly or indirectly synchronized. ArrayList is not thread safe and its methods are not synchronized. LinkedList is also not thread safe.
  4. LinkedList is implemented by a two-way list, and the data index needs to be traversed from the beginning, so the random access efficiency is low, but it does not need to move the data when inserting elements, and the insertion efficiency is high.

What is the difference between HashMap and Hashtable

  1. HashMap is a lightweight implementation of Hashtable. HashMap allows the key and value to be null, but at most one record key is allowed to be null. HashTable does not allow it.
  2. The methods in HashTable are thread safe while HashMap is not. Accessing HashMap from multiple threads requires an additional synchronization mechanism.
  3. Hashtable uses Enumeration to traverse, and HashMap uses Iterator to traverse.

What is the difference between fail-fast and fail-safe iterators

  1. Fail-fast is performed directly on the container. During the traversal process, once the data in the container is found to be modified, a ConcurrentModificationException will be thrown immediately, resulting in traversal failure. Common containers that use the fail-fast method include HashMap and ArrayList.
  2. The fail-safe traversal is based on a clone of the container. Therefore, modification of the content in the container does not affect the traversal. Common containers that are traversed in a fail-safe manner include ConcurrentHashMap and CopyOnWriteArrayList.

In HashSet, the relationship between equals and hashCode

The two methods equals and hashCode are inherited from the object class. equals is mainly used to determine whether the memory address reference of the object is the same address; hashCode converts the memory address of the object into a hash according to the defined hash rules code. The elements stored in the HashSet cannot be repeated, and the two methods of hashCode and equals are used to judge whether the stored objects are the same:

  1. If the hashCode values ​​of the two objects are different, it means that the two objects are not the same.
  2. If the hashCode values ​​of the two objects are the same, then the equals method of the object will be called. If the return result of the equlas method is true, then the two objects are the same, otherwise they are not the same.

Java reflection principle

Java will load all classes at compile time and save their meta information to the Class class object. Therefore, methods such as x.class/x.getClass()/Class.forName() can be designed to obtain Class objects. Therefore, when the Field/Method/Constructor object is called by reflection, further operations can be performed according to the Class class object. 

Dynamic proxy implementation

  1. Use the JDK reflection mechanism to implement the proxy interface
  2. Use CGLib to generate subclasses for the specified class and perform proxy.

Brief description of OOM (out of memory)

When the JVM allocates insufficient memory, an out of memory exception will be thrown. When creating a new large object, OOM exceptions are prone to occur 

Briefly describe ArrayList expansion

If the storage space of ArrayList after adding new elements is not enough, ArrayList will use the expansion mechanism, that is, apply for 1.5 times the original space in memory, and copy the value of the original array to the new array to complete the expansion. 

Java set Collection type

Linked List List: ArrayList, Vector, LinkedList Collection Set: Hashset, LinkedHashSet, TreeSet Table Map: HashMap, TreeMap, HashTable 

New features in Java 1.8

  1. Added lambda expression
  2. New functional interface
  3. Add stream api
  4. Hashmap and concurrenthashmap achieve underlying optimization
  5. The jvm memory layout has been revised, and the metadata area has replaced the permanent generation

Guess you like

Origin blog.csdn.net/weixin_46601559/article/details/126433096