Two sides of bytes - what are synchronization locks, deadlocks, optimistic locks, pessimistic locks

The season of gold, silver and silver is  coming soon . It is a good time to look for a job. You must seize the opportunity to find your favorite high-paying job. If you are looking for a job, you can’t do without an interview. From now on, let’s brush up on the interview questions and find out what’s missing! ! !

c19f2664af5646ed82170b1ca3efb141.png


content

1. Object-Oriented Features

2. What are the basic data types in Java

3. Differences between JDK JRE JVM

4. The difference between overloading and rewriting

5. Difference between == and equals in Java

6. The difference between String, StringBuffer, StringBuilder

7. What is the difference between an interface and an abstract class

8. What are the commonly used methods of string

9. What is the singleton pattern? How many are there?

10. Reflection

11. Java exceptions

12. What is the difference between BIO, NIO, and AIO

13. Synchronized locks, deadlocks, optimistic locks, pessimistic locks

14. Talk about the underlying implementation principle of synchronized

15. What is the difference between synchronized and volatile

16. What is the difference between synchronized and Lock

17. Handwritten bubble sort


1. Object-Oriented Features

Object-oriented features: encapsulation, inheritance, polymorphism, abstraction.

 Encapsulation : It is to combine the attributes and behavior (data) of the object into an independent whole, and to hide the internal implementation details of the object as much as possible, that is, to hide the things that you don't want to tell or should not be told to others, and to expose the things that can be told to others, Others can only implement the requirements with the functions I provide, but do not know how to implement them. Increase security.

Inheritance : The subclass inherits the data attributes and behaviors of the parent class, and can expand new behaviors according to its own needs, which improves the reusability of the code.

Polymorphism : Refers to allowing different objects to respond to the same message. That is, the same message can adopt a variety of different behaviors depending on the sending object (sending a message is a function call). Encapsulation and inheritance are almost all prepared for polymorphism. During execution, the actual type of the referenced object is determined, and its corresponding method is called according to its actual type.

Abstract : It represents an abstract concept derived from the analysis and design of the problem domain. It is an abstraction of a series of concrete concepts that look different but are essentially the same. In Java, abstract is modified with the abstract keyword. When a class is modified with abstract, this class cannot be instantiated. It can be seen from this that abstract classes (interfaces) exist for inheritance. 


2. What are the basic data types in Java

Basic data types: byte, short, int, long, char, float, double, boolean .

  type of data number of bytes number of digits
Integer byte 1 8
short 2 16
int 4 32
long 8 64
floating point float 4 32
double 8 64
boolean boolean 1 8
character type char 2 16

 


3. Differences between JDK JRE JVM

JDK (Java Development Kit) is the core of the entire Java, is the java development kit, including the Java runtime environment JRE, Java tools and Java basic class library.

JRE (Java Runtime Environment) is a collection of environments necessary to run JAVA programs, including the java virtual machine and some core class libraries of java programs.

JVM is the abbreviation of Java Virtual Machine (Java Virtual Machine).


4. The difference between overloading and rewriting

Overloading : Occurs in the same class, the method name must be the same, the parameter type is different, the number is different, the order is different, the method return value and access modifier can be different, and it occurs at compile time.

Override : Occurs in parent and child classes, the method name and parameter list must be the same, the return value range is less than or equal to the parent class, the thrown exception range is less than or equal to the parent class, and the access modifier range is greater than or equal to the parent class; if the parent class method access modifier If the character is private, subclasses cannot override this method.


5. Difference between == and equals in Java

The role of == :
  Basic type: The comparison is whether the value is the same
  Reference type: The comparison is whether the address value is the same
. The role of equals :
  Reference type: By default, the comparison is the address value.


Note : equals in class libraries such as String, Integer, and Date are rewritten, and the content is compared instead of the address!


6. The difference between String, StringBuffer, StringBuilder

String String constants :

The String class in String uses the final keyword to modify the character array to save the string, private final char value[], and the String object is immutable, which can be understood as a constant and thread-safe.


AbstractStringBuilder is the common parent class of StringBuilder and StringBuffer, and defines some basic operations on strings, such as expandCapacity, append, insert, indexOf and other public methods.
StringBuffer string variable (thread safe)

StringBuffer  adds a synchronization lock to the method or adds a synchronization lock to the called method, so it is thread-safe.


StringBuilder string variable (not thread safe)

StringBuilder does not synchronize the method, so it is not thread-safe.


summary:

(1) If you want to operate a small amount of data, use String;

(2) StringBuffer is used to operate a large amount of data under the multi-threaded operation of the string buffer;

(3) StringBuilder is used to operate a large amount of data under the single-threaded operation of the string buffer.


7. What is the difference between an interface and an abstract class

Implementation: Subclasses of abstract classes use extends to inherit; interfaces must use implements to implement interfaces.

Constructor: An abstract class can have a constructor; an interface cannot.

main method: An abstract class can have a main method and we can run it; an interface cannot have a main method.

Number of implementations: A class can implement many interfaces; however, it can only inherit from one abstract class.

Access modifier: methods in interfaces are decorated with public by default; methods in abstract classes can be any access modifier


8. What are the commonly used methods of string

indexOf(): Returns the index of the specified character.

charAt(): Returns the character at the specified index.

replace(): String replacement.

trim(): Remove the blanks at both ends of the string.

split(): splits a string and returns an array of split strings.

getBytes(): Returns a byte type array of strings.

length(): Returns the length of the string.

toLowerCase(): Convert the string to lowercase letters.

toUpperCase(): Convert the string to uppercase characters.

substring(): Intercept string.

equals(): String comparison.


9. What is the singleton pattern? How many are there?

Singleton mode : An instance of a class will only be created once in a multi-threaded environment. There are three types of singleton mode: hungry singleton mode, lazy singleton mode and double-checked singleton mode.

Hungry Chinese style : thread-safe, initialized at the beginning.

Lazy : Not thread safe, lazy initialization.

Double-checked locking : thread-safe, lazy initialization.


10. Reflection

The reflection mechanism in Java means that in the running state, any class can know all the properties and methods of this class; and for any object, any method of it can be called; this dynamic acquisition of information and dynamic The ability to invoke an object's method becomes the reflection mechanism of the Java language .


There are 3 ways to get a Class object:

Call the getClass() method of an object

Person p=new Person();

Class clazz=p.getClass();

Call the class attribute of a class to get the Class object corresponding to the class

Class clazz=Person.class;

Use the forName() static method in the Class class (safest/best performance)

Class clazz=Class.forName("full path of class"); (most commonly used)


11. Java exceptions

Throwable is the parent class for error handling in all Java programs. There are two resource classes: Error and Exception. 

 Error : Indicates an unpredictable error detected by the JVM. Since this is a serious error at the JVM level, the JVM cannot continue to execute. Therefore, this cannot be caught, and no recovery action can be taken. Error messages can be displayed.

Exception : Represents a recoverable exception, which is catchable.


 1. Runtime exceptions : They are all exceptions of the RuntimeException class and its subclasses, such as NullPointerException (null pointer exception), IndexOutOfBoundsException (subscript out of bounds exception), etc. These exceptions are unchecked exceptions, which can be captured and processed in the program, or not deal with. These exceptions are generally caused by program logic errors, and the program should avoid the occurrence of such exceptions as much as possible from a logical point of view. The characteristic of runtime exception is that the Java compiler does not check it, that is, when such an exception may occur in the program, even if it is not caught with a try-catch statement and thrown with a throws clause statement, it will also be thrown. Compiled.
2. Non-runtime exception (compilation exception) : It is an exception other than RuntimeException, which belongs to the Exception class and its subclasses. From the perspective of program syntax, it is an exception that must be handled. If it is not handled, the program cannot be compiled. Such as IOException, SQLException, etc., as well as user-defined Exception exceptions, generally do not customize checked exceptions.


Common RunTime exceptions are as follows :

NullPointerException - Null pointer reference exception 
ClassCastException - Type casting exception. 
IllegalArgumentException - Illegal argument passed exception. 
ArithmeticException - Arithmetic operation exception  ArrayStoreException  Store an object in an 
array that is incompatible with the declared type. 
IndexOutOfBoundsException - Subscript out of bounds exception  abnormal




12. What is the difference between BIO, NIO, and AIO

BIO : Block IO synchronous blocking IO is the traditional IO we usually use. It is characterized by simple and convenient mode and low concurrent processing capability.

NIO : New IO synchronous non-blocking IO is an upgrade of traditional IO. The client and server communicate through Channel (channel) to achieve multiplexing.

AIO : Asynchronous IO is an upgrade of NIO, also called NIO2, which implements asynchronous non-blocking IO. The operation of asynchronous IO is based on events and callback mechanisms.


13. Synchronized locks, deadlocks, optimistic locks, pessimistic locks

Sync lock:

Problems can easily arise when multiple threads access the same data at the same time. In order to avoid this situation, we need to ensure that the threads are synchronized and mutually exclusive, which means that multiple threads executing concurrently, only one thread is allowed to access the shared data at the same time. In Java, you can use the synchronized keyword to acquire a synchronized lock on an object.

Deadlock:

What is a deadlock is that multiple threads are blocked at the same time, and one or all of them are waiting for a resource to be released.

Optimistic locking:

Always assume the best situation. Every time you go to get the data, you think that others will not modify it, so it will not be locked, but when you update it, you will judge whether others have updated the data during this period. You can use the version number mechanism and CAS algorithm implementation. Optimistic locks are suitable for multi-read application types, which can improve throughput. Like the write_conditio mechanism provided by the database, they are actually provided optimistic locks. The atomic variable class under the java.util.concurrent.atomic package in Java is implemented using CAS, an implementation of optimistic locking.

Pessimistic lock:

Always assume the worst case, every time you go to get the data, you think others will modify it, so every time you get the data, you will lock it, so that others who want to get the data will block until it gets the lock (shared resource It is only used by one thread at a time, other threads are blocked, and resources are transferred to other threads after they are used up). Many such lock mechanisms are used in traditional relational databases, such as row locks, table locks, read locks, write locks, etc., all of which are locked before operations are performed. Exclusive locks such as synchronized and ReentrantLock in Java are the realization of the pessimistic lock idea.


14. Talk about the underlying implementation principle of synchronized

Synchronized can ensure that when a method or code block is running, only one method can enter the critical section at the same time, and it can also ensure the memory visibility of shared variables.

Every object in Java can be used as a lock, which is the basis for synchronized to achieve synchronization:

  • Ordinary synchronization method, the lock is the current instance object
  • Static synchronization method, the lock is the class object of the current class
  • Synchronized method block, lock is the object inside the brackets

15. What is the difference between synchronized and volatile

The essence of volatile is to tell the jvm that the value of the current variable in the register (working memory) is uncertain and needs to be read from the main memory; synchronized locks the current variable, only the current thread can access the variable, and other threads are blocked. .

volatile can only be used at the variable level; synchronized can be used at the variable, method, and class level.

Volatile can only achieve the modification visibility of variables and cannot guarantee atomicity; while synchronized can guarantee the modification visibility and atomicity of variables.

Volatile will not cause thread blocking; synchronized may cause thread blocking.

Variables marked volatile are not optimized by the compiler; variables marked synchronized can be optimized by the compiler.


16. What is the difference between synchronized and Lock

First of all, synchronized is a java built-in keyword. At the jvm level, Lock is a java class;

Synchronized cannot determine whether to acquire the lock status, Lock can determine whether to acquire the lock;

synchronized will automatically release the lock (a thread will release the lock after executing the synchronization code; b will release the lock if an exception occurs during the execution of the thread), Lock needs to manually release the lock in finally (unlock() method releases the lock), otherwise it is easy to cause the thread to die Lock;

Using the synchronized keyword for both thread 1 and thread 2, if the current thread 1 acquires the lock, the thread 2 thread waits. If thread 1 is blocked, thread 2 will wait all the time, and the Lock lock will not necessarily wait. If you try to acquire the lock, the thread can end without waiting all the time;

Synchronized locks are reentrant, uninterruptible, and unfair, while Lock locks are reentrant, judging, and fair (both possible);

Lock locks are suitable for synchronization problems with a large number of synchronized codes, and synchronized locks are suitable for synchronization problems with a small amount of code.


17. Handwritten bubble sort

public class Sort {
    public static void sort() {
        Scanner input = new Scanner(System.in);
        int sort[] = new int[10];
        int temp;
        System.out.println("请输入10个排序的数据:");
        for(int i = 0;i < sort.length;i++){
            sort[i] = input.nextInt();
        }
        for(int i = 0;i < sort.length - 1;i++){
            for(int j = 0;j < sort.length - i - 1;j++){
                if(sort[j] < sort[j+1]){
                    temp = sort[j];
                    sort[j] = sort[j+i];
                    sort[j+i] = temp;
                }
            }    
        }
        System.out.println(""排列后的顺序为:);
        for(int i = 0;i<sort.length;i++){
            System.out.print(sort[i]+"===");
        }
    }
}

 If this article is helpful to my friends, I hope to give a like and support~ Thank you very much~

af5df094dca5421b8adabbb28e99e5e3.gif


 

Guess you like

Origin blog.csdn.net/weixin_42306958/article/details/122973102