[JAVA Web] 5 interview questions

[JAVA Web] 5 interview questions

Add a note: My original intention is Java Each technology stack organizes 100 interview questions, and the current foundation is Nezha's "208 Interview Questions"
In the future, I will add my valuable questions and real interview questions, and I will also re-modify some of the mistakes in the questions.
Anyway, it will not be used for profit purposes, sorting and self-learning, there are places taken from others, please understand and be grateful   
                                                                   --Dumb Buyiku

1. What is the difference between JSP and Servlet?
2. What built-in objects does JSP have? What are the functions?
3. What is the difference between forward and redirect?
4. Talk about the 4 scopes of JSP
5. What is the difference between session and cookie?

6. Is String str="i" the same as String str=new String("i")?
7. How to reverse a string?
8. What are the commonly used methods of the String class?
9. How many objects will new String("a")+new String("b") create?
10. What is the difference between ordinary class and abstract class?

11. What is the difference between interface and abstract class?
12. How many types of IO streams are there in Java?
13. What is the difference between BIO, NIO, and AIO?
14. What are the common methods of Files?
15. What is reflection?
16. What is Java serialization? When is serialization required?
17. Why use cloning? How to achieve object cloning? What is the difference between deep copy and shallow copy?
18. What is the difference between throw and throws?
19. What is the difference between final, finally, and finalize?
20. In try-catch-finally, if there is a return in the catch, will finally still be executed?

21. What are the common exception classes?
22. What method is hashCode()? what's the effect?
23. What classes are there for manipulating strings in Java? What's the difference between them?
24. What are the reference types in Java?
25. In Java, why is it not allowed to access non-static variables from static methods?
26. Talk about the naming convention of JavaBean
27. Analysis of JavaBean attribute naming specification problems?
28. What is the memory model of Java?
29. Give an example of when you would prefer to use an abstract class instead of an interface?
30. What are the ways to instantiate objects?

31. What is the byte type 127+1 equal to?
32. What are the Java containers?
33. What is the difference between Collection and Collections?
34. What is the difference between List and Set?
35. What is the difference between HashMap and Hashtable?
36. Tell me about the implementation principle of HashMap?
37. What are the implementation classes of Set?
38. Talk about the implementation principle of HashSet
39. What is the difference between ArrayList and LinkedList?
40. How to realize the conversion between array and List collection?

41. What is the difference between poll() and remove() in Queue?
42. Which collection classes are thread safe?
43. What is iterator Iterator?
44. How to use Iterator? What are the characteristics?
45. What is the difference between Iterator and ListIterator?
46. ​​How to ensure that a collection cannot be modified?
47. What are queues and stacks? What's the difference?
48. Why did ConcurrentHashMap abandon the segment lock when Java8 started?
49. Why does ConcurrentHashMap (JDK8) use synchronized instead of reentrant locks such as ReentranLock?
50. What is the difference between ConcurrentHashMap and HashTable?

51. What is the difference between HashMap and HashSet?
52. Please talk about ReadWriteLock and StampedLock
53. What is the difference between run() and start() of a thread?
54. Why does the run() method execute when we call the start() method, why can't we call the run() method directly?
55. Have you ever used Synchronized? What is its principle?
56. What optimizations does the JVM make to Java's native locks?
57. Why wait(), notify() and notifyAll() are in Object class?
58. How does Java implement communication and collaboration between multiple threads?
59. What is the function of the yield() method in the Thread class?
60. Why is Synchronized an unfair lock?

61. Please talk about the characteristics of volatile, why can it guarantee the visibility of variables to all threads?
62. Why is Synchronized a pessimistic lock? What is the implementation principle of optimistic locking? What is CAS? What features does it have?
63. Is optimistic locking necessarily good?
64. Please compare the similarities and differences between Synchronized and ReentrantLock as detailed as possible
65.
66. What is lock elimination and lock coarsening?
67. Compared with Synchronized, what is the difference in the implementation principle of reentrant lock ReentrantLock?
68. So please talk about the AQS framework?
69. How does AQS share resources?
70. How to synchronize Java threads with each other?

71. What synchronizers do you know? Please introduce them separately
72. How is the thread pool in Java implemented?
73. What are the core construction parameters for creating a thread pool?
74.
75. What is the function of the volatile keyword?
76. Since volatile can guarantee the visibility of variables between threads, does it mean that operations based on volatile variables are concurrently safe?
77. What is ThreadLocal? What are the usage scenarios?
78. Please talk about how ThreadLocal solves concurrency security?
79. Many people say that ThreadLocal should be used with caution. Tell me about your understanding. What should you pay attention to when using ThreadLocal?
80. Why is the code reordered?

81. What is spin?
82. What is the principle of synchronized lock upgrade in multithreading?
83. What is the difference between synchronized and ReentrantLock?
84. What is the Lock interface (Lock Interface) in the Java Concurrency API? What are its advantages over synchronous?

1. What is the difference between JSP and Servlet?

1.Servlet is server side Java program, which acts as an intermediate layer between the client and the server

2.JSP full name is Java Server Pages,Chinese is Java server page,
Its essence is a simplified servlet design.
JSP is a dynamic page design whose main purpose is to move presentation logic from Servlet separated out.

3.JVM can only recognize Java code, not recognized JSP,
JSP After compilation becomes Servlet,
web The container will JSP The code compiles to JVM Recognizable Java kind( Servlet)

4.JSP There are built-in objects, Servlet no built-in objects

2. What built-in objects does JSP have? What are the functions?

JSP Nine built-in objects:
1.pageContext,the page context object,
Equivalent to the collection of all functions in the page
 through which you can obtain JSP page out,request,response,session,application object

2.request
3.response

4.session

5.application,application object,
application Realize the sharing of data among users, and can store global variables,
It starts at server startup and continues until server shutdown

6.page,that is JSP itself

7.exception

8.out,out used in web The output information in the browser,
And manage the output buffer on the application server, the scope is page

9.config,Get server configuration information

3. What is the difference between forward and redirect?

1. forward is a direct request forwarding
   redirect It is an indirect request forwarding, also called redirection
  
2. forward: Client and browser execute a request
   redirect: The client and the browser execute the request twice
   
3. forward: classic MVC mode is forward
   redirect: Used to avoid abnormal access by users
   For example, users access abnormally, Servlet you can put HTTP The request redirects to the login page
   
4. forward: Address unchanged
   redirect: address change
   
5. forward Common methods:
   RequestDispatcher Category forward()method
   redirect Common methods:
   HttpServletRequest Category sendRedirect()method

4. Talk about the 4 scopes of JSP

page 

request

session

application

5. What is the difference between session and cookie?

1.storage location is different
cookie in the client browser
session on the server

2.different storage capacity
cookie < 4K,Up to 20 are reserved for one site cookie
session No upper limit, under server protection
session Do not store too many things in memory, and set session delete mechanism

3.different storage methods
cookie only save ASCII string and needs to be stored encoded as Unicode character or binary data
session Any type of data can be stored in it, including but not limited to String,integer,list,map wait

4.different privacy policy
cookie Visible to clients, not secure
session Stored on the server, secure

5.The validity period is different
 Development can be done by setting cookie properties to achieve cookie long term results
session depends on the named JESSIONID of cookie,
and cookie JSESSIONID The expiration time defaults to-1,
Just close the window and the session will fail,
thus session Can't achieve long-term effective effect

6.Different in cross-domain support
cookie Support cross-domain
session Does not support cross-domain

6. Is String str="i" the same as String str=new String("i")?

String str="i"  Will first look in the constant pool i,
If the constant pool exists i,will i assign the address of the variable str
 If the constant pool does not exist i,just create a i Then assign the newly created address to the variable str

String str=new String("i")
The object will be allocated in the heap space, even if the content is the same, a new object will be recreated

7. How to reverse a string?

Generate a string as an argument StringBuilder object
 Then stringBuilder.reverse()method implements inversion
 that is, through stringBuilder object call reverse()method implementation

public class Test{
	public static void main(String[] args){
		String str = "abcdefg";
		StringBuilder stringBuilder = new StringBuilder(str);
		String ret = stringBuilder.reverse().toString();
		System.out.println(ret);		
	}
}

8. What are the commonly used methods of the String class?

One: common String class get function
length(): Get the length of the string
charAt(int index): Get the character at the specified index position
indexOf(char ch):Gets the index position of the first occurrence of the specified character in the string
substring(int start): Intercept the string from the specified position, default to the end
substring(int start,int end): 
Intercept the string from the specified position to the specified position

Two: common String Class Judgment Function
equals(Object obj): Determine whether the content of the string is the same, case sensitive
contains(String str): Determine whether the specified string is contained in the string
startsWith(String str): Determine whether the string starts with the specified string
endsWith(String str): Determine whether the string ends with the specified string
isEmpty(): Determine whether the string content is an empty string""

Three: common String class conversion function
byte[] getBytes(): convert string to byte array
char[] toCharArray():convert string to character array
String valueOf(char[] chars): 
Convert a character array to a string, valueOf()The method can convert any type to a string

Four: common String Other functions of the class
replace(char old,char new): Replace the specified old character with the new character
replace(String old,String new): Replace the specified old string with the new string
trim(): Remove spaces at both ends
int compartTo(String str):
first according to ASCII Table, perform subtraction from the first letter, and return the result of this subtraction
 If the first few letters are exactly the same, then the subtraction operation will be performed according to the length of the two strings, and the result of the subtraction will be returned
 If the two strings are exactly the same, return 0

9. How many objects will new String("a")+new String("b") create?

Object 1: new StringBuilder()
The underlying concatenated string creates a StringBuilder object

object 2: new String("a")

Object 3: put in the string constant pool"a"(If there is no previous string constant pool"a"if)

Object 4: new String("b")

Object 5: put in the string constant pool"b"(If there is no previous string constant pool"b"if)

Object 6: call stringBuilder.toString()method will new StringBuilder("ab")

With particular emphasis on: stringBuilder.toString()The call is not generated in the string constant pool"ab"

10. What is the difference between ordinary class and abstract class?

One: Is it possible to instantiate aspects
 Ordinary classes can instantiate
 Abstract classes cannot be instantiated

Two: Is there an abstract method aspect
 Ordinary classes have no abstract methods
 A class with abstract methods must be an abstract class, and abstract classes can have abstract methods, only need to declare, no need to implement
 A subclass of an abstract class must implement all the abstract methods in the abstract class, otherwise the subclass is still an abstract class

Three: The modifier aspect of the method
 abstract methods cannot be static modify
 Because the abstract method has no method body, if it is static, the class can call the method directly, which is meaningless
 abstract methods cannot be final modify
 Subclasses of an abstract class must implement all abstract methods in the abstract class, and are final Decorated methods cannot be overridden

11. What is the difference between interface and abstract class?

One: Modifiers
 For interface interface modifier modification
 for abstract classes abstract modifier modification
 
 Two: Inheritance
 A class can implement multiple interfaces
 Abstract classes can only inherit single inheritance
 
 Three: method body
 interface: JDK8 Before, the methods in the interface were all abstract methods, without method body
       JDK8 After that, static methods can be defined in the interface, and static methods must have a method body
	             Ordinary methods in interfaces have no method body and must be implemented

 Abstract class: can contain abstract methods and non-abstract methods, non-abstract methods must have a method body
 
 Four: Subcategories
 Subclasses that implement an interface must implement all abstract methods of all interfaces
 
 If a class inherits an abstract class:
 1.Subclasses may not be abstract if all abstract methods are implemented
 2.If all abstract methods are not implemented, the subclass is still an abstract class

12. How many types of IO streams are there in Java?

One: Distinguish by flow direction
 input stream and output stream

Two: Distinguish by transmission unit
 byte stream and character stream
 byte stream: inputStream and outputStream
 Character stream: reader and writer

13. What is the difference between BIO, NIO, and AIO?

one: BIO: synchronous blocking
BIO: connect one thread at a time
JDK 1.4 Previously, when establishing a network connection, the BIO model,
Start the server first socket,Then start the client socket,
For server-side communication, after the client sends a request, it first determines whether the server has a thread response,
If not, it will wait forever or be rejected,
If there is, it will wait for the end of the request to continue execution

two: NIO: synchronous non-blocking
NIO mainly to solve BIO The big concurrency problem, BIO One thread is allocated for each request, and there are multiple requests for one connection
 When there are too many requests, each thread occupies a certain memory space, and the server is paralyzed

three: AIO: asynchronous non-blocking
AIO: One valid request per thread
JDK7 start supporting AIO,Suitable for structures with a large number of connections and relatively long connections
 For example, the album server, fully call OS Participate in concurrent operations

14. What are the common methods of Files?

method:
exist()
createFile()
createDirectory()
write()
read()
copy()
size()
delete()
move()

15. What is reflection?

The so-called reflection is Java the ability to self-observe at runtime,
pass class(),constructor(),field(),method()Four methods to get the various components of a class

exist Java In the runtime environment, for any class, you can know which properties and methods the class has.
This function of dynamically obtaining class information and dynamically calling methods of objects comes from the reflection mechanism.

16. What is Java serialization? When is serialization required?

Serialization is a mechanism for handling streams of objects. Stream the content of the object, and transfer the streamed object across the network

Serialization is achieved by serializable An interface that has no methods that need to be implemented,
implements Serializable Just to mark that the object is serializable,
use an output stream(FileOutputStream)to construct a ObjectOutputStream object,
then use ObjectOutputStream Object writeObject(Object object)method can pass parameters object Objects are written out to disk,
Use the input stream when you need to restore

For example, you can serialize an object and then pass HTTP pass Internet Transfer the object between client and server.
On the other end, deserialization will construct objects from the stream hub.

Generally, when the program is running, objects are generated, and these objects disappear with the stop of the program, but we want to save some objects,
At this time, we can save the object to disk through serialization, and obtain the previously saved object through deserialization when we need to use it.

The main purpose of object serialization is to transfer and save objects, and preserve the integrity and transferability of objects.

For example, when transferring over a network or saving an object as a local file, you need to use serialization.

17. Why use cloning? How to achieve object cloning? What is the difference between deep copy and shallow copy?

One: Why use cloning?
If you want to copy an object, but also want to save the original object for the next operation, you need to clone it at this time

Two: How to implement object cloning?
accomplish Cloneable interface, override clone()method
 accomplish Serializable Interface, realize cloning through object serialization and deserialization, can realize real deep cloning
BeanUtils,apache,and Sprng are provided bean tools, except it's all shallow clones.

Three: What is the difference between deep copy and shallow copy?
Shallow copy: only the basic data types are cloned, and the reference data types are not cloned.
Photocopy: Cloning both basic data types and reference data types

18. What is the difference between throw and throws?

one: throw
 Acting in the method, it means that a specific exception is thrown, which is handled by the statement in the method body
 code goes to throw An exception must be thrown when

two: throws
 It acts on the declaration of the method, indicating that an exception is thrown, and the caller handles the exception.
code goes to throws An exception may or may not occur when

19. What is the difference between final, finally, and finalize?

one: final
final Can modify classes, variables, methods
final Modified classes cannot be inherited, final Modified variables cannot be reassigned after assignment. final Decorated methods cannot be overridden

two: finally
finally for throwing exceptions, finally The statement in the code block will be executed regardless of whether an exception occurs finally,Commonly used to close some streams

three: finalize()The method is called during garbage collection
 In general, we do not need to implement finalize()method, when the object is recycled, some resources need to be released, such as releasing socket connect

but when calling finalize()method doesn't mean GC The object will be recycled immediately, so when it is possible to actually call, the object does not need to be recycled.
Then when it is time to recycle, because it was called once before, it is not called again this time, causing problems, so it is not recommended to use finalize()method

20. In try-catch-finally, if there is a return in the catch, will finally still be executed?

20.try-catch-finally in, if catch middle return up, finally Will it still be implemented?

public class Test{
	private static int test(){
		try{
			int ret = 1/0;
			System.out.prinln("try");
		}catch(Exception e){
			System.out.println(e.getMessage());
			return 1;
		}finally{
			System.out.println("finally");
		}
	}
	public static void main(String[] args){
		System.out.println(test());
	}
}

Console output:
/by zero
finally
1

Conclusion: the sequence is catch =>finally =>catch middle return

21. What are the common exception classes?

1.NullPointerException: null pointer exception
2.SQLException: Database related exceptions
3.IndexOutOfBoundsException: Array subscript out of bounds exception
4.FileNotFoundException: Thrown when opening a file fails
5.IOException: when something happens IO exception thrown when
6.ClassCastException: This exception is thrown when an attempt is made to cast an object to a subclass that is not an instance
7.NoSuchMethodException:When a method cannot be found, throws
8.ArrayStoreException: Exception thrown when trying to store an object of the wrong type into an array of objects
9.NumberFormatException:When trying to convert a string to a number, it fails and throws an exception
10.IllegalArgumentException:The exception thrown indicates that an illegal or incorrect parameter was passed to the direction
11.ArithmeticException: This exception is thrown when an abnormal operation condition occurs. For example, when an integer is divided by zero, an instance of this class is thrown

22. What method is hashCode()? what's the effect?

Java of Object The class has a method:
    public native int hashCode()
	
one: hashCode()The role of the method
hashCode()The method is mainly used with hash-based collections, such as HashSet,HashMap,HashTable

When the collection needs to add new elements, first call the object's hashCode()method to get the corresponding hashCode value,
actually hashMap there will be one of table Save the objects that have been stored in hashCode value,
if table does not exist in the hashCode value, it is stored directly, if there is, it is called equals()method to compare with the new element,
If it is the same, it will not be stored, if it is different, it will be stored

two: equals()and hashCode()Relationship
 if equals()The method is true,hashCode()Must be equal
 if equals()The method is false,hashCode()not necessarily unequal

if hashCode()equal in value, equals()not necessarily equal
 if hashCode()the values ​​are not equal, equals()must not be equal

Three: Rewrite equals()method, be sure to override hashCode()method

Four: Baidu Encyclopedia

hashCode()The method returns the hash code value of the object, which is supported to provide some advantages for the hash table,
For example: java.util.Hashtable provided hash table

hashCode The general agreement for is:
exist Java Called multiple times on the same object during application execution hashCode()method must consistently return the same integer,
The premise is that the object equals()The information used in the comparison has not been modified.
The integer need not be consistent from one execution of an application to another execution of the same application

if according to equals(Object)method, two objects are equal,
then on each of the two objects call hashCode()methods must all produce the same integer result

The following situations are not required:
if according to equals(java.lang.Object)method, two objects are not equal, then call on either of the two objects hashCode()methods are bound to produce distinct integer results.
However, programmers should be aware that producing distinct integer results for unequal objects can improve hash table performance.

In fact, by Object class defined hashCode()method does return different integers for different objects.
(This is normally done by converting the object's internal address to an integer, but JavaTM Programming languages ​​do not require such implementation tricks)

when equals()When a method is overridden, it is often necessary to override hashCode()method,
to maintain hashCode()The general contract of the method, which states that equal objects must have equal hash codes

Five: Xiaobai's explanation
1.hashCode It is used for searching. If you have studied data structures, you should know that in the chapter of searching and sorting, for example, there are such locations in memory
0 1 2 3 4 5 6 7
 And I have a class, this class has a field called ID,I want to store this class in one of the above 8 places,
if not hashCode()Method and stored arbitrarily, then when searching, you need to search these eight locations one by one, or use algorithms such as dichotomy.
But if use hashCode()Then the efficiency will be improved a lot.

Our class has a field called ID,Then we define our hashCode value is ID%8,
Then store our class in the location where the remainder is obtained. such as our ID for 9,9 The remainder of dividing by 8 is 1, then we store the class in the position of 1,
if ID is 13, and the remainder obtained is 5, then we put this class in the position of 5,
This way, later lookups for the class can be done by ID Divide by 8 to find the remainder and directly find the location where the class is stored.

2.But if two classes have the same hashCode What should I do? (We assume the class above ID field is not unique),
For example, the remainder of dividing 9 by 8 and 17 by 8 is 1, so is this illegal? The answer is: it is legal.
So what about a more accurate judgment? At this point it is necessary to redefine equals()method of judging

That is, we first pass hashCode value to determine whether two classes are stored in the same bucket, but there may be many classes in this bucket,
Then we need to pass equals()method to find the class we want to find in this bucket

So, rewrite the equals()method, why rewrite hashCode()Woolen cloth?
Think about it, if you want to find something in a bucket, you must first find the bucket,
we need to first pass hashCode Value to determine which bucket to put in, and then pass equals()method to determine which value

23. What classes are there for manipulating strings in Java? What's the difference between them?

one: String
String is an immutable object, each time the String A type change creates a new object

two: StringBuidler
 Thread is not safe, high efficiency, mostly used for single thread

three: StringBuffer
 Thread safety, due to locking reasons, the efficiency is not as good as StringBuilder,Multi-threaded

Conclusion: infrequent string operations use String,It is not recommended to use frequently String

Efficiency of performing string modification:
StringBuilder > StringBuffer > String

24. What are the reference types in Java?

(1).strong reference
Java The default statement in is a strong reference, for example:
Object obj = new Object();
obj = null;

As long as the strong reference exists, the garbage collector will never reclaim the referenced object.
If you want to be recycled, you can set the object to null

(2).soft reference(SoftReference)
When there is enough memory, soft references will not be recycled
 Only when the memory is insufficient, the system will reclaim the soft reference object.
If there is still not enough memory after recycling the soft reference object,
A memory overflow exception will be thrown.

byte[] buff = new byte[1024*1024]
SoftReference<byte[]> sr = new SoftReference<>(buff);

(3).weak reference(WeakReference)
Weak references are reclaimed during garbage collection

(4).phantom reference(PhantomReference)

(5).reference queue(ReferenceQueue)

Reference queues can be used in conjunction with soft references, weak references, and phantom references
 When the garbage collector is about to reclaim an object, if it finds that it still has references,
It will add this reference to the reference queue before recycling the object.

The program can judge whether a reference is added to the reference queue,
To determine whether the referenced object will be reclaimed by the garbage collector,
This allows some necessary action to be taken before the object is recycled.

25. In Java, why is it not allowed to access non-static variables from static methods?

1.Static variables belong to the class itself, memory is allocated when the class is loaded, and can be directly accessed through the class name
2.Non-static variables belong to the object of the class. Only when the object of the class is generated, memory will be allocated and accessed through the instance of the class.
3.The static method also belongs to the class itself, but there is no instance of the class at this time, and there are no non-static variables in memory, so it cannot be called

26. Query employee information whose employee name starts with S

1.JavaBean The class must be a public class, set the class access to public
2.JavaBean Classes must have an empty constructor:
The class must have a public constructor with no parameters,
This constructor should also set default values ​​for attributes by calling each attribute's setter method
3.one JavaBean Classes should not have public instance variables, class variables are all private
4.Holding values ​​should be passed through a set of accessor methods(getXxx and setXxx)to visit:
For each characteristic, there should be a common getter and setter Private instance variables for the method.

The property is of boolean type, you can use isXxx()method instead getXxx()method
 Usually attribute names are to be distinguished from package names, class names, method names, field names, and constant names
 First of all: English must be used, not Hanyu Pinyin

(1).Bag(package)
It is used to classify the classes that complete different functions and put them in different directories(Bag)Down,
Package naming rules: Reverse the company domain name as the package name. for example www.sohu.com
 For package names: every letter needs to be lowercase.
for example: com.sohu.test under the package Test The full name of the class is: com.sohu.test.Test.java

If the class is defined without using package,
So Java It is assumed that the classes we define are located in the default package(default package)

(2).kind
 Capitalize the first letter, if a class consists of multiple words,
Then the first letter of each word is capitalized, and no hyphens are used in between.
Use English as much as possible, such as ConnectionFactory

(3).method
 The first letter is all lowercase, if a method consists of multiple words,
Then capitalize the first letter from the second word without using a hyphen, such as addPerson

(4).field
 Same as method. like ageOfPerson

(5).constant
 All letters of all words are uppercase, if there are multiple words, then use underscores to connect
 like: public static final int AGE_OF_PERSON = 20;
usually with static use together

27. Query employee information containing M in employee name

1.JavaBean Attribute naming should use the conventional camel case naming rules as much as possible
2.Try to avoid using a letter in the first word of the attribute name: such as eBook,eMail
3.boolean Attribute names avoid using " is"name that starts with
4.along with JDK,eclipse,spring With the continuous improvement of the software version,
The problems in the lower version may be solved in the higher version
 The original normal code of the lower version may no longer be supported in the higher version environment

28. What is the memory model of Java?

in understanding what is Java Before the memory model, let's understand why it is proposed Java memory model

As mentioned earlier, there are three major problems with concurrent programming
CPU cache, on multi-core CPU In the case of
 The switching of the current execution thread by the operating system brings atomicity problems
 Compiler instruction rearrangement optimization brings order problems
 In order to solve the three major problems of concurrent programming,
came up with JSP-133,new Java memory model, JDK5 start using

Brief summary
Java The memory model is JVM a specification of
 A specification that defines the behavior of shared memory read and write operations in multithreaded programs
 Shields the access differences of various hardware and operating systems,
promise Java The memory access effect of the program is consistent under various platforms

Ways to solve concurrency problems: limit processor optimization and use memory barriers
 Three synchronization primitives are enhanced(synchronized,volatile,final)memory semantics of
 Defined happens-before rule

29. Query the number, name, time of entry, and department number of employees who joined in 1981

Both interfaces and abstract classes follow the design principle of "facing the interface rather than implementing the code",
It can increase the flexibility of the code and can adapt to changing needs.
Here are a few points to help you answer this question:
exist Java In , you can only inherit from one class, but can implement multiple interfaces.
So once you inherit a class, you lose the opportunity to inherit other classes.

Interfaces are often used to represent ancillary descriptions or behaviors
 like: Runnable,Cloneable,Serializable etc.
So when you use abstract classes to represent behavior,
Your class can't be both Runnable,Cloneable,Serializable
(Note: The meaning here is that if the Runnable etc. are implemented as abstract classes),
Because Java You cannot inherit two classes in
 But when you use interfaces, your class can have multiple different behaviors at the same time.

In some applications with high time requirements, abstract classes tend to be used, which are slightly faster than interfaces.
If you want to standardize a series of behaviors in the class inheritance hierarchy,
and can code better in the same place, then abstract classes are a better choice.
Sometimes, interfaces and abstract classes can be used together,
The function is defined in the interface, and the default implementation is defined in the abstract class

30. What are the ways to instantiate objects?

(1).new to create new objects

(2).clone()

(3).created by reflection
    Class<?> cls = Class.forName("com.dao.User");
	User u = (User)cls.newInstance();

(4).serialization deserialization
 Serialization
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:/data.txt"));
out.writeObject(user1);
out.close();

deserialization
ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:/data.txt"));
User user2 = (User)in.readObject();
System.out.println("deserialization user: "+user2);
in.close();

31. What is the byte type 127+1 equal to?

byte range is-128~127

The byte length is 8 bits, the leftmost is the sign bit
 And the binary of 127 is 01111111,
so execute+1 When operating, 01111111 becomes 10000000

As we all know, negative numbers are stored in the computer, and the first bit on the left is the sign bit.

Then the negative number's complement is converted to decimal as follows:
If a number is positive, its original code, complement code and complement code are the same
 A positive number's complement, convert it to decimal, you can directly convert

Knowing the complement of a negative number, convert it to a decimal number, the steps are as follows:
1.Negate everyone first
2.convert it to decimal number
3.Add minus sign, then subtract 1

For example, 10000000, the highest bit is 1, which is a negative number
1.Reverse everyone and get 01111111
2.Converted to decimal number is 127
3.Add a negative sign and subtract 1 to get-128

32. What are the Java containers?

(1).Collection
1.list
ArrayList,LinkedList,Vector

2.Set
HashSet,TreeSet

(2).Map
HashMap,Hashtable,TreeMap

33. What is the difference between Collection and Collections?

(1).Collection is the most basic collection interface,
Collection derived two subinterfaces list and set,Two different storage methods are defined

(2).Collections is a wrapper class that contains various static methods related to collection operations
(Searching, sorting, thread-safety, etc. on collections)
This class cannot be instantiated, just like a utility class, serving Collection frame

34. What is the difference between List and Set?

(1).List Introduction
 There are actually two List: 
one is basic ArrayList,The advantage is that random access to elements
 the other is LinkedList,It is not designed for fast random access, but fast insertion or deletion
ArrayList: realized by array List. Allows fast random access to elements,
but to List The speed of inserting and removing elements in the middle is very slow
LinkedList: Optimized for sequential access, to List Intermediate insertions and deletions are not expensive.
Random access is slower
LinkedList Also has the following methods: addFirst(),addLast(),getFirst(),getLast(),
removeFirst()and removeLast(),these methods(is not defined in any interface or base class)
make LinkedList Can be used as stacks, queues and bidirectional queues

(2).Set Introduction
Set have with Collection Exactly the same interface, so without any extra functionality.
actually Set that is Collection,Just behave differently.
This is a typical application of the idea of ​​inheritance and polymorphism: expressing different behaviors.
Set Do not save duplicate elements(As for how to judge that the elements are the same, it is more responsible)

Set: deposit Set Each element of must be unique, because Set Duplicate elements are not saved. join in Set The elements must be
 definition equals()method to ensure object uniqueness. Set and Collection have exactly the same interface.
Set Interfaces do not guarantee that the order of elements is maintained.

(3).List and Set the difference
1.List,Set are inherited from Collection
2.List Features: Elements are placed in order, elements can be repeated,
Set Features: Elements have no order of placement, elements cannot be repeated, and repeated elements will be overwritten.
(Set Although the elements have no order of placement, the elements are in Set The position in the is determined by the element's HashCode determined by the value,
whose position is fixed, adding Set of Object must be defined equals()method)
in addition List support for Looping, that is, traversing through subscripts, or using iterators,
but Set Only iterators can be used, because he is out of order and cannot use subscripts to obtain the desired value.

3.Set and List Compared:
Set: Retrieval of elements is inefficient, deletion and insertion are efficient, and insertion and deletion do not cause element position changes
List: and array types, List It can grow dynamically and find elements efficiently.
Inserting and deleting elements is inefficient because it will cause the position of other elements to change.

35. What is the difference between HashMap and Hashtable?

1.HashMap is thread-unsafe, Hashtable is thread safe

2.HashMap Allow keys and values ​​in null,Hashtable not allowed

3.HashMap The default container is 15, which is 2 times the expansion
Hashtable The default container is 11, for 2x+1 expansion

36. Tell me about the implementation principle of HashMap?

One: Introduction
HashMap based on Map Interface, elements are stored as key-value pairs, allowing null value,
HashMap is thread-unsafe

Two: basic attributes
 initial size, HashMap The default is 16, 2 Double expansion
 load factor is 0.75
 initialized default array
size
threshold,Determine whether adjustments are required HashMap capacity

three: HashMap storage structure
JDK7 in the array+Storage form of linked list
HashMap take Entry array to store key-value,Each key-value pair forms a Entry entity,
Entry The class is actually a one-way linked list structure, which has next pointer to the next Entry entity,
use this to solve Hash Conflict issues.
HashMap implement an inner class Entry,Important attributes are hash,key,value,next

JDK8 in the array+linked list+The storage form of the red-black tree. When the length of the linked list exceeds the threshold 8,
Convert the linked list to a red-black tree to further improve performance.

37. What are the implementation classes of Set?

(1).HashSet
HashSet yes Set the implementation class of the interface,
Set The main implementation class below is HashSet,(That is the most used)
Beside this there is TreeSet and LinkedHashSet and TreeSet
HashSet is unordered and non-repeatable.
through the object HashCode()and equals()method guarantees the uniqueness of the object.

(2).TreeSet
TreeSet How to sort elements:
If the element itself has a comparison function, it needs to be implemented Comparable interface, and override CompareTo()method
 If the element itself does not have a comparison function, it needs to implement Comparator interface, and override compare()method

(3).LinkedHashSet
LinkedHashSet is an orderly Set A collection, that is, the order in which its elements are stored and output is the same.

38. Talk about the implementation principle of HashSet

HashSet actually a HashMap Instance, the data storage structure is an array+linked list
HashSet is based on HashMap achieved, HashSet The elements in are stored in HashMap of key above,
and value is a unified object PRESENT 

private static final Object PRESENT = new Object();

HashSet middle add()The method call is the underlying HashMap middle put()method, put()method to determine whether the inserted value exists,
and HashSet of add()method,
First determine whether the element exists
 do not insert if present
 Insert if not present
 This guarantees HashSet There are no duplicate values ​​in

through the object hashCode()Methods and equals()method guarantees the uniqueness of the object

39. What is the difference between ArrayList and LinkedList?

ArrayList It is the data structure implementation of dynamic array, and the efficiency of searching and traversing is high
LinkedList It is a data structure of a doubly linked list, and the efficiency of adding and deleting is higher

40. How to realize the conversion between array and List collection?

public class Test{
	public static void main(String[] arts){
		String[] arr = {"zs","ls","ww"};
		List<String> list = Arrays.asList(arr);
		System.out.println(list);
		
		ArrayList<String> list1 = new ArrayList<String>();
		list1.add("Zhang San");
		list1.add("Li Si");
		list1.add("Wang Wu");
		String[] arr1 = list1.toArray(new String[list1.size()]);
		System.out.println(arr1);
		for(int i = 0; i < arr1.length; i++){
			System.out.println(arr1[i]);
		}
	}
}

41. What is the difference between poll() and remove() in Queue?

one: offer()Methods and add()Method difference:
When adding a new item, if the queue is full,
use add()method throws an exception
 use offer()method will return false

two: poll()Methods and remove()Method difference:
poll()Methods and remove()The method is to delete the first element from the queue,
When the first element of the queue does not exist,
use remove()Throw an exception,
use poll()method returns null

three: peek()Methods and element()method:
peek()Methods and element()The method is used to query the head element of the queue
 When the queue head element is empty
 use element()method throws an exception
 use peek()method returns null

42. Which collection classes are thread safe?

one: Vector: than ArrayList One more synchronization mechanism (thread safety)

two: Stack: The stack, also thread-safe, inherits from Vector

three: HashTable: than HashMap There is an additional thread safety mechanism.

Four: ConcurrentHashMap: It is an efficient but thread-safe collection.

43. What is iterator Iterator?

In order to facilitate the processing of elements in the collection, Java An object appears in
 This object provides some methods to deal with the elements in the collection specifically,
such as removing and getting elements in a collection,
This object is called an iterator ( Iterator). 

44. How to use Iterator? What are the characteristics?

Iterator Methods in the interface source code:
1.java.lang.Iterator interface is java.util.Collection interface inheritance,
java.util.Collection interface iterator()method returns a Iterator object

2.hasNext()Check if there are more elements in the collection

3.next()method to get the next element in the collection

4.remove()The method deletes the newly returned element of the iterator

45. What is the difference between Iterator and ListIterator?

one: ListIterator inherit Iterator

two: ListIterator Compare Iterator many ways
1.add(E e) Insert the specified element into the list, the insertion position is before the current position of the iterator
2.set(E e) replaces the argument with the last element returned by the iterator e
3.hasPrevious() The current position of the iterator, traverse the collection in reverse to determine whether it contains elements
4.previous() The current position of the iterator, traverse the collection in reverse, and get the next element
5.previousIndex() The current position of the iterator, traverse the collection in reverse, and return the subscript of the next element
6.nextIndex() The current position of the iterator, returns the subscript of the next element

Three: the scope of use is different,
Iterator It is possible to iterate over all collections
ListIterator Can only be used for traversal List Collections and their subclasses
1.ListIterator have add()method, you can List Add objects in , while Iterator cannot
2.ListIterator have hasPrevious()and previous()method, can achieve reverse traversal, and Iterator cannot
3.ListIterator have nextIndex()and previousIndex()method to locate the position of the current index, while the Iterator cannot
4.ListIterator have set()method, it is possible to realize the List modification, and Iterator Can only be traversed, cannot be modified

46. ​​How to ensure that a collection cannot be modified?

We can easily think of using final keywords to modify

final Keywords can modify classes, methods, member variables,
final Modified classes cannot be inherited,
final Decorated methods cannot be overridden,
final Modified member variables must be initialized with values
 If this variable is a basic data type, it means that the value of this variable cannot be changed
 If this member variable is a reference type, it means that the address value of this reference cannot be changed.
But the content pointed to by this reference can still be modified.

We can do an experiment:
As you can see, we use final keyword defines a Map Collection, at this time we pass values ​​into the collection
 The first key-value pair is(1,1),Then we modify, we can put key Change the value of 1 to 100,
Explain that we can modify Map set of values

So what should we do to ensure that the collection is not modified?
we can use Collection Packaged unmodifiableMap(Map)method,
returned by this method Map It cannot be modified, if it is modified, it will be reported java.lang.UnsupportedOperationException abnormal
 In the same way: Collection package also provides support for List and Set collection method
Collections.unmodifiableList(List)
Collections.unmodifiableSet(Set)

public class Test{
	public static void main(String[] args){
		Map<String,String> hashMap = new HashMap<String,String>();
		hashMap.put("1","zhangsan");
		hashMap.put("2","lisi");
		hashMap.put("1","wangwu");
		
		Map<String,String> hashMap1 = Collections.unmodifiableMap(hashMap);
		hashMap1.put("3","zs");
		System.out.println("unmodifiableMap,"+hashMap1);
	}
}

47. What are queues and stacks? What's the difference?

One: Queue first in first out, stack first in last out

Two: Traversing data at different speeds
 The stack can only take data from the head, that is, the first to be put in needs to traverse the entire stack before it can be taken out.
Moreover, when traversing the data, it is necessary to open up a temporary space for the data to maintain the consistency of the data before traversing.

The queue is different, he traverses based on the address pointer, and can traverse from the beginning or the end,
But it cannot be traversed at the same time, and there is no need to open up temporary space, because the data structure is not affected during the traversal process, and the speed is much faster

48. Why did ConcurrentHashMap abandon the segment lock when Java8 started?

ConcurrentHashMap The principle is to refer to the internal Segment(ReentranLock)segment lock,
Guaranteed to operate in different segments Map When , it can be executed concurrently,
Operate the same segment Map When, the lock competition and waiting are carried out.
So as to achieve thread safety, and the efficiency is greater than synchronized

But when Java8 after, JDK However, this strategy was abandoned in favor of synchronized+CAS  

Reason for deprecation:
pass JDK According to the source code and official documents, they believe that the reasons for deprecating segment locks are as follows:
Adding multiple segment locks wastes memory space
 In production environment, Map The probability of competing for the same lock when putting it in is very small, and the segmented lock will cause a long wait for updates and other operations

To improve GC The efficiency of the new synchronization scheme is:
The source code is preserved segment code, but does not use

49. Why does ConcurrentHashMap (JDK8) use synchronized instead of reentrant locks such as ReentranLock?

One: the granularity of the lock
 First of all, the granularity of the lock has not become thicker, but has even become finer.
Whenever the capacity is expanded, ConcurrentHashMap The concurrency is doubled

two: Hash conflict
JDK7 middle, ConcurrentHashMap from the second time hash The way(Segment->HashEntry)Elements that can be quickly found.
exist JDK8 through the array+linked list+The form of red-black tree makes up the put(),get()performance gap
JDK8 in ConcurrentHashMap When expanding,
Other threads can decide whether to check the linked list by checking the nodes in the array(red black tree)to expand,
Reduce the granularity of capacity expansion and improve the efficiency of capacity expansion

why is synchronized,instead of ReentranLock Woolen cloth?

One: Reduce memory overhead
 Assuming reentrant locks are used for synchronization support, each node needs to inherit AQS for synchronization support.
But not every node needs to get synchronization support,
Only the head node of the linked list(The root node of the red-black tree)Synchronization is required, which undoubtedly brings a huge waste of memory


Two: get JVM support
 Reentrant locks are, after all, API At this level, there is little room for subsequent performance optimization
synchronized is JVM directly supported, JVM Can make corresponding optimization measures at runtime: lock coarsening, lock elimination, lock spin, etc.
This makes synchronized able to follow JDK The performance can be improved by upgrading the version without changing the code.

50. What is the difference between ConcurrentHashMap and HashTable?

ConcurrentHashMap Combines HashMap and HashTable The advantages
HashMap It is not synchronized, but it is efficient in single-threaded cases
HashTable It is to ensure the correctness of program execution in the case of synchronization

ConcurrentHashMap The locking approach is fine-grained.
ConcurrentHashMap Will Hash Divided into 16 buckets (the default),
such as get(),put(),remove()Wait for common operations to lock only the buckets that are currently needed

ConcurrentHashMap read concurrency, since most of the reads are not locked,
So read operations are almost completely concurrent operations, just asking for size()only need to lock the entire Hash

And when iterating, ConcurrentHashMap Another iteration method that is different from the fail-fast iterators of traditional collections is used, that is, weakly consistent iterators.
In the weakly consistent iterator approach, when iterator Will not throw if the collection changes after being created ConcurrentModificationException,
Instead, when changing new new data rather than affecting the original data,
iterator After completion, replace the head pointer with new data, so iterator when using the original data

51. What is the difference between HashMap and HashSet?

One: first understand HashCode
Collection Interface has two subclasses: 1.List  2.Set
List:The elements are ordered and can be repeated
Set: Elements are not required and cannot be repeated

If you want to ensure that the elements are not repeated, what should you use to judge?
This requires Object.equals()method, but if there are many elements, adding an element must be judged n times? Obviously this is unrealistic.

then Java The principle of the hash table is adopted.
Hash algorithm, also known as hash algorithm, is to directly assign data to an address according to a specific algorithm.
Beginners can simply understand that, hashCode()What the method returns is the physical location where the object is stored (it's not).

In this way, when a new element is added to the collection,
call this element first hashCode()method, just locate the physical location where it should be placed.
If there is no element at this position, it can be directly stored at this position
 If there is an element at this position, call its equals()method to compare with the new element,
If it is the same, it will not be saved, if it is not the same, it will be hashed to other locations
 The advantage is that this way to call equals()The number of methods is greatly reduced

Summary: When searching for collection elements, hashCode()The existence of the method can greatly reduce the object equals()Method comparison times to improve search efficiency

Java for eqauls()Methods and hashCode()The method is defined as follows:
1.equals()two objects that are equal, HashCode The value must be the same
equals()Two objects whose methods are not equal, Hashcode()Equality is possible (hash collisions occur due to the randomness of hash code generation).
2.HashCode The value is the same, the two objects are not necessarily the same, equals()May or may not be equal
Hashcode()Don't wait, it will be released equals()do not wait

two: HashMap and HashSet What is the difference?
1.implement the interface
HashMap accomplish Map interface
HashSet accomplish Set interface

2.storage content
HashMap Store key-value pairs
HashSet storage object

3.method of adding elements
HashMap use put()method add element
HashSet use add()method add element

4.what calculation to use hashCode value
HashMap use key calculate hashCode value
HashSet Calculated using member objects hashCode value,For two objects, hashCode values ​​may be the same, so continue with equals()method to determine whether the object content is the same,
Returns if the two objects are different false

5.running speed
HashMap Compare HashSet quick


52. Please talk about ReadWriteLock and StampedLock

ReadWriteLock Includes two seed locks
1.ReadWriteLock yes JDK5 The read-write split lock provided in
ReadWriteLock Multiple read locks can be implemented at the same time, but read and write and write and write are mutually exclusive, and only one write lock thread is in progress
 read-read not exclusive:No blocking between reads and reads.
read-write mutex:Read blocks write, write also blocks read
 Write-write mutex:write block
2.StampedLock
StampedLock yes JDK8 Provides a read-write lock, compared with ReentrantReadWriteLock better performance
 because ReenTrantReadWrtieLock It is mutually exclusive between reading and writing, using a pessimistic strategy,
ReenTrantReadWrtieLock The disadvantage is: in the case of too many reading threads, it will cause the writing thread to be in a starvation state.
Although it can be set to true Designated as fair, but the throughput went down again
 and StampedLock is to provide an optimistic strategy,
The advantage is better implementation of read and write separation, and the throughput will not drop

StampedLock Includes three seed locks
1.write lock WriteLock
WriteLock is an exclusive write lock
 When a thread acquires the lock, other threads requesting read or write locks are blocked.
On success, it returns a stamp(Credentials) variable to represent the version of the lock,
Called when the lock is released unlockWrite()method passing stamp parameter, providing a non-blocking acquisition lock tryWriteLock
2.pessimistic read lock readLock
readLock Is a shared read lock that multiple threads can acquire if no thread acquires a write lock.
If there is a write lock acquired, other threads requesting read locks will be blocked.
Pessimistic read locks will think that other programs may modify the data they operate, so they need to lock the data first.
This is considered in the case of less reading and more writing.
Request the lock successfully and return a stamp value,
Called when the lock is released unlockRead()method passing stamp parameter, providing a non-blocking lock acquisition method tryReadLock 
3.optimistic read lock tryOptimisticRead
tryOptimisticRead Compared with pessimistic read lock, it does not pass before operating data CAS set the state of the lock,
Returns a non-zero if no thread has acquired the write lock stamp variable,
get the stamp After that, you need to call before operating the data validate()method to determine whether a thread has acquired a write lock during the period,
If the return value is 0, a thread acquires the write lock.
If not 0 you can use stamp Variable locks to manipulate data.
because tryOptimisticRead The lock state is not modified, so there is no need to release the lock.
This is considered in the case of more reads and fewer writes, and does not involve CAS operation, so the efficiency is higher
 To ensure data consistency, it is necessary to copy a copy of the variable to be operated to the method stack.
And when operating data, other writing threads may have modified the data,
And what we operate is the data in the method stack, which is a snapshot.
So the most recent data is not returned, but the consistency is guaranteed.

53. What is the difference between run() and start() of a thread?

Each thread runs through a specific Thread The method corresponding to the object run()to complete its operation,
run()A method is called a thread body.
by calling Thread Category start()method to start a thread.

run()Method used to execute the thread's runtime code
start()method is only used to start the thread

run()can be called repeatedly
start()can only be called once

start()method to start a thread, and truly realize multi-threaded operation.
transfer start()method without waiting run()The method body code is executed,
You can continue to execute other codes directly.
At this point the thread is in a ready state and is not running.
then pass this Thread class call method start()to complete its running state,
run()method finishes running, the thread terminates, and CPU Then schedule other threads.

run()The method is in this thread, just a method in the thread, not multi-threaded.
If you call directly run()The method is actually equivalent to calling an ordinary method.
call directly run()method must wait run()After the method is executed, the following code can be executed.
So there is still only one execution path, and there is no multi-threaded feature at all.
So when multi-threaded execution should be used start()method instead of run()method

54. Why does the run() method execute when we call the start() method, why can't we call the run() method directly?

new one Thread class, the thread enters the new state
 transfer Thread Category start()method, will start a thread and make the thread into the ready state
 When the time slice is allocated, it can start running
start()The corresponding preparation work for the thread will be performed, and then executed automatically run()The code in the method, this is the real multi-threaded work

while directly executing run()method, will put run()method as a main Ordinary methods under the thread to execute
 does not execute it in a new thread, so this is not multi-threaded work

Summary: call start()method to start the thread and put the thread into the ready state,
and run()method is just thread An ordinary method call, or executed in the main thread

55. Query employee information whose salary is the same as any employee in department 20

(1).Reentrancy
synchronized There is a counter in the lock object of(recursions variable)It will record how many times the thread acquires the lock
1.The benefits of reentrancy
2.deadlock can be avoided
3.It allows us to better encapsulate the code

(2).uninterruptible
1.After one thread acquires the lock, another thread must be in a blocking or waiting state if it wants to acquire the lock.
If the first thread does not release the lock, the second thread will always block or wait and cannot be interrupted
2.synchronized non-interruptible
3.Lock lock()method is uninterruptible
4.Lock tryLock()method is interruptible

56. What optimizations does the JVM make to Java's native locks?

(1).spin lock
 When the thread is blocked, first let the thread spin and wait for a period of time,
Maybe other threads have been unlocked during this time,
At this time, there is no need to allow the thread to perform blocking operations.

(2).adaptive spin lock
 The upgrade of the spin lock, the number of spins is no longer fixed, it is determined by the previous number of spins and the status of the lock owner

(3).lock elimination
 When compiling synchronous code blocks dynamically,
JIT The compiler uses escape analysis technology to determine whether the lock object is only accessed by one thread,
And there are no other threads, then the lock can be canceled

(4).lock coarsening
 when JIT The compiler finds that a series of operations repeatedly lock and unlock the same object,
Even if the lock operation occurs in the loop, the scope of lock synchronization will be coarsened to the outside of the entire operation series

Lock granularity: don't lock some irrelevant code

Lock coarsening: Don’t lock and execute multiple times if it can be executed at one time

57. Why wait(), notify() and notifyAll() are in Object class?

Java In , any object can act as a lock, and wait(),notify()The wait method is used to wait for the lock of the object or wake up the thread,
exist Java There is no lock available for any object in the thread,
So if you want any object to be callable, the method must be defined in Object in class

Some people will say that since the thread gives up the object lock, it can also be wait()defined in Thread in class
 Newly defined threads inherit from Thread class, there is no need to redefine wait()implementation of the method.
However, there is a very big problem with this. A thread can hold many locks.
When a thread wants to give up the lock, which lock should you give up?
Of course, this design is not impossible, but it is more complicated to manage

In summary, wait(),notify()and notifyAll()method to be defined in Object in class

58. How does Java implement communication and collaboration between multiple threads?

Inter-thread communication and collaboration can be achieved through interrupts and shared variables

For example, the most classic producer-Consumer model:
When the queue is full, the producer needs to wait for the queue to have space before continuing to put items into it
 During the waiting period, the producer must release the critical resources(and queue)possession of
 Because if the producer does not release the right to occupy critical resources,
Then the consumer will not be able to consume the items in the queue, and there will be no room for the queue
 Then the producer will wait indefinitely.
therefore. Under normal circumstances, when the queue is full, the producer will surrender the right to occupy critical resources and enter the suspended state.
Then wait for the consumer to consume the goods, and then the consumer has space through the producer queue.
Similarly, when the queue is empty, the consumer must also wait,
Waits for the producer to notify it that there is an item in the queue.
This process of communicating with each other is the collaboration between threads.

Java The two most commonly used methods of thread communication and cooperation:
1.synchronized locked thread Object Category wait()or notify()or notifyAll()
2.ReentrantLock class locked thread Condition Category await()or signal()or signalAll()

Direct data exchange between threads
 Inter-thread communication via pipes: 1.byte stream 2.character stream

59. What is the function of the yield() method in the Thread class?

yield()What should be done is to return the currently running thread to a runnable state,
to allow other threads of the same priority to get a chance to run.
therefore yield()The purpose is to allow threads of the same priority to be properly executed in rotation,
However, in practice there is no guarantee yield()To achieve the purpose of concession,
Because the yielded thread may be selected again by the thread scheduler.

in conclusion: yield()Never caused the thread to go to wait or sleep or block state
 In most instances, yield()will cause the thread to go from the running state to the runnable state,
but it may not work

60. Why is Synchronized an unfair lock?

When the lock is released, any thread has the opportunity to compete for the lock
 The purpose of this is to improve the efficiency
 But the disadvantage is that thread starvation may occur

61. Please talk about the characteristics of volatile, why can it guarantee the visibility of variables to all threads?

volatile It can only act on variables, which guarantees the visibility and order of operations, but does not guarantee atomicity

exist Java The memory model is divided into main memory and working memory.
Java The memory model stipulates that all variables are stored in main memory,
Each thread has its own working memory

The interaction between main memory and working memory is divided into 8 atomic operations
1.lock()
2.unlock()
3.read()
4.load()
5.assign()
6.use()
7.store()
8.write()

volatile Modified variables, only for volatile conduct assign operate,
only then load,only load only then use,
This ensures that the working memory operation volatile Variables are synchronized to main memory

62. Why is Synchronized a pessimistic lock? What is the implementation principle of optimistic locking? What is CAS? What features does it have?

Synchronized The concurrency strategy is pessimistic, no matter whether there is competition or not, any data operation must be locked

The core of optimistic locking is CAS,
CAS Include memory value, expected value, new value
 Only if the memory value is equal to the expected value, the memory value will be modified to the new value

63. Is optimistic locking necessarily good?

Optimistic locking believes that operations on an object will not cause conflicts
 So each operation does not lock, but only verifies whether there is a conflict when the change is submitted at the end,
If there is a conflict, try again until it succeeds. The process of this attempt is called spin

Optimistic locking is not locked
 But optimistic locking introduces ABA problem, at this time the version number is generally used for control
 There may also be problems with too many spins
 At this time, the efficiency cannot be improved, but it is not as efficient as direct locking
 It can only guarantee the atomicity of an object, which can be encapsulated into an object, and then CAS operate 

64. Please compare the similarities and differences between Synchronized and ReentrantLock as detailed as possible

One: Similarities
 They are all blocking synchronization,
That is to say, when a thread acquires the object lock and enters the code block, other threads that access the synchronization block must be blocked outside the synchronization code block and wait.

Two: functional difference
Synchronized yes Java The keywords of the language are mutually exclusive at the level of the native grammar and require JVM accomplish
ReentrantLock yes JDK5 provided after API A level mutex that requires Lock()and unlock()Method fit try/finally code block to complete
Synchronized use more ReentrantLock more convenient
 Fine-grained and flexible locks: ReentrantLock Stronger than Synchronized

Three: performance difference
Synchronized After the introduction of biased locks and spin locks, the performance of the two is similar.
In this case, the official recommendation is to use Synchronized
1.Synchronized
Synchronized Will be formed before and after the sync block respectively monitorenter and monitorexit two bytecode instructions
 in execution monitorenter instruction, it first tries to acquire the object lock.
If the object is not locked, or the current thread already owns the object lock, set the lock counter+1,
corresponding execution monitorexit when the counter-1,When the counter is 0, the lock is released.
If acquiring the lock fails, the current thread will block until the object lock is released by another thread.

2.ReentrantLock
ReentrantLock yes java.util.concurrent A set of mutex locks provided under the package,
compared to Synchronized,ReentrantLock The class provides some advanced functions, mainly as follows:
Waiting can be interrupted. When the thread holding the lock is not released for a long time, the waiting thread can choose to give up waiting.
This is equivalent to Synchronized To avoid deadlock situations, the lock.lockInterruptibly()to implement this mechanism;
Fair lock, when multiple threads are waiting for the same lock, they must acquire the locks in the order in which they were applied for.
Unfair lock: ReentrantLock The default is an unfair lock, you can pass the parameter true Set to a fair lock, but the performance of the fair lock is not very good
 The lock binds multiple conditions, one ReentrantLock An object can bind multiple objects at the same time.
ReentrantLock provided a Condition(condition) class, which is used to wake up the threads that need to be woken up in groups,
instead of like Synchronized Either wake up a thread at random, or wake up all threads.

## 65. Reverse the string
select reverse('hello') from dual;

66. What is lock elimination and lock coarsening?

One: lock elimination
 Lock elimination means that the virtual machine is synchronized according to whether an object actually exists
 If there is no synchronization, the access to the object does not need to be locked and unlocked

for example StringBuffer of append()method because append()The method needs to determine whether the object is occupied,
And if there is no lock competition in the code, then this part of the performance consumption is meaningless.
So the virtual machine will optimize the above code when it compiles in real time, that is, lock elimination

    @Override
    public synchronized StringBuffer append(String str){
        toStringCache = null;
        super.append(str);
        return this;
    }

As can be seen from the source code, append()method used synchronized keyword, it is thread-safe.
But we may only put the StringBuffer used as local variables;
StringBuffer It is only valid within the scope of the method, and there is no problem of thread safety.
At this time, we can optimize it through the compiler to eliminate the lock,
The premise is Java must run on server mode, escape analysis must be enabled at the same time

-server -XX:+DoEscapeAnalysis -XX:+EliminateLocks
 in+DoEscapeAnalysis Indicates that escape analysis is enabled,+EliminateLocks Indicates lock removal

    public static String createStringBuffer(String,str1,String str2){
        StringBuffer sBuf = new StringBuffer();
        sBuf.append(str1);//The append() method is a synchronous operation
        sBuf.append(str2);
        return sBuf.toString();
    }
 
Escape analysis: such as the above code, it depends on sBuf Is it possible to escape its scope?
if will sBuf Returned as the return value of the method,
Then it may be used as a global variable outside the method, and thread safety problems may occur
 then you can say sBuf This object has escaped, so it should not be append()operation of lock removal,
But our code above does not have lock escape, and lock elimination can bring about a certain performance improvement.

Two: lock coarsening
 The request, synchronization, and release of locks will consume certain system resources.
If high-frequency lock requests are not conducive to the optimization of system performance
 Lock coarsening is to combine multiple lock requests into one request to expand the scope of locks.
Reduce the performance consumption caused by lock request, synchronization and release

70. Compared with Synchronized, what is the difference in the implementation principle of reentrant lock ReentrantLock?

1.reentrant lock

2.ReentrantLock internally implemented Sync,Sync inherited from AQS abstract class.
Sync There are two implementations, one is a fair lock and the other is an unfair lock, defined by the constructor.
AQS maintains a state To calculate the number of reentries to avoid thread problems caused by frequent hold and release operations.

3.ReentrantLock Only code blocks can be defined
 and Synchronized Methods and code blocks can be defined.

4.Synchronized yes JVM An internal keyword of the
 and ReentrantLock yes JDK5 one introduced after API level mutex

5.Synchronized Realize automatic lock and release lock,
and ReentrantLock You need to manually lock and release the lock, and you can pause in the middle

6.Synchronized Due to the introduction of biased locks and spin locks, the performance is comparable to ReentrantLock almost,
But it is much more convenient to operate, so it is preferred to use Synchronized

68. So please talk about the AQS framework?

1.AQS yes AbstractQueuedSynchronized abbreviation of
 it provides a FIFO queue
 It can be seen as a core component that implements synchronization locks

AQS It is an abstract class, mainly used through inheritance
 It itself does not implement any synchronous interface,
Just define the method of acquisition and release of synchronization state to provide custom synchronization components

2.AQS Two functions of: exclusive lock and shared lock

3.AQS Internal implementation of:

AQS The implementation of relies on the internal synchronization queue, that is, FIFO two-way queue,
If the current thread fails to compete,
So AQS Will construct the current thread and wait state information into a Node Join the synchronization queue and block the thread at the same time,
When the thread that acquires the lock releases the lock, it wakes up a blocked node (thread) from the queue

AQS What is maintained inside the queue is a FIFO doubly linked list,
The characteristic of this structure is that each data structure has two pointers,
Point to the direct successor node and direct predecessor node respectively.
Therefore, the doubly linked list can easily access the predecessor and successor nodes from any node.
each Node In fact, it is encapsulated by threads,
When the thread fails to compete for the lock, it will be encapsulated into Node add to AQS in queue

69. How does AQS share resources?

AQS Define two resource sharing methods
1.Exclusive(Exclusive)
Exclusive lock: Only one thread can execute, such as ReentrantLock. 
Can be divided into fair lock and unfair lock
 Fair lock: According to the order in which threads are arranged in the queue, the first comer gets the lock first
 Unfair lock: When a thread wants to acquire a lock, it ignores the order of the queue and directly grabs the lock. Whoever grabs it will own it

2.Share(shared)
Multiple threads can execute simultaneously,
like Semaphore,CountDownLatch,CyclicBarrier,ReadWriteLock wait

ReentrantReadWriteLock It can be seen as a combination,
because ReentrantReadWriteLock That is, a read-write lock allows multiple threads to read a resource at the same time.

Different custom synchronizers contend for shared resources in different ways.
Custom synchronizers only need to implement shared resources when implementing state The acquisition and release methods are sufficient,
As for the maintenance of the specific thread waiting queue, such as entering the queue or waking up the queue after failing to obtain resources, etc.,
AQS Already implemented at the top level

70. How to synchronize Java threads with each other?

1.synchronized

2.volatile

3.ReentrantLock

4.Thread synchronization using local variables

71. What synchronizers do you know? Please introduce them separately

1.Semaphore Synchronizer
 feature:
The classic semaphore controls access to shared resources through counters
Semaphore(int count): create owned count semaphores for licenses
acquire()/acquire(int num): get 1/num licenses
release()/release(int num): release 1/num licenses

2.CountDownLatch Synchronizer
 feature:
A specified number of events must occur before it can continue to run (such as a race, the referee calls out 3, 2,1 Then everyone runs at the same time)
CountDownLatch(int count): must happen count number to open the latch
await(): wait latch
countDown(): trigger event

3.CyclicBarrier Synchronizer
 feature:
It is suitable for execution only when multiple threads have reached the predetermined point (such as Doudizhu, you need to wait for three people to start)
CyclicBarrier(int num): number of waiting threads
CyclicBarrier(int num,Runnable action): Number of waiting threads and what to do when all threads arrive
await(): Suspend the thread after reaching the critical point

4.switch ( Exchanger)Synchronizer

5.Phaser Synchronizer

72. How is the thread pool in Java implemented?

Create a blocking queue to hold the tasks,
Create enough threads when executing the task for the first time, and process the task,
After that, each worker thread automatically obtains threads from the task queue until the number of tasks in the task queue is 0, and the thread is in a waiting state at this time.
Once a work task is added to the task queue, the worker thread is immediately awakened for processing to achieve thread reusability.

A thread pool generally consists of four basic components:
1.thread pool manager
 Used to create thread pools, destroy thread pools, and add new tasks

2.worker thread
 Threads in the thread pool can perform tasks cyclically, and are in a waiting state when there are no tasks

3.task queue
 It is used to store unprocessed tasks, a caching mechanism.

4.task interface
 The interface that each task must implement, for the worker thread to schedule the execution of the task,
Mainly stipulates the start and finish of the task and the status of the task

73. What are the core construction parameters for creating a thread pool?

Java Complete constructor for thread pool

public ThreadPoolExecutor{
    int corePoolSize;// The minimum number of threads maintained by the thread pool for a long time, even if the thread is in the Idle state, it will not be recycled
    int maximumPoolSize;// The upper limit of the number of threads
    long keepAliveTime;// thread maximum lifetime
    TimeUnit unit;// time unit
    BlockingQueue<Runnable> workQueue;// task queue
    ThreadFactory threadFactory;// thread factory
    RejectedExecutionHandler handler;// Deny task handler
}

74. Keep n to y decimal places and round up

select round(3.1415.3) from dual;

75. What is the function of the volatile keyword?

For visibility, Java provided volatile keywords to ensure visibility and prohibit instruction rearrangement
volatile supply happens-before guarantee,
Make sure that modifications made by one thread are visible to other threads.
When a shared variable is volatile when retouching,
It will ensure that the modified value will be updated to main memory immediately,
When other threads need to read, it will go to memory to read new values

From a practical point of view, volatile An important role of the CAS Combined, atomicity guaranteed
 For details, see java.util.concurrent.atomic The classes under the package, such as AtomicInteger

volatile Often used for single operations in a multi-threaded environment,
such as single read or single write

76. Since volatile can guarantee the visibility of variables between threads, does it mean that operations based on volatile variables are concurrently safe?

volatile There is no consistency problem in the modified variables in the working memory of each thread
 In memory where each thread works, volatile Modified variables also have inconsistencies
 However, since the data in the main memory is refreshed to the working memory before each use,
The execution engine cannot see the inconsistency, so it can be assumed that there is no inconsistency
 but Java The operation of is not an atomic operation, resulting in volatile Not thread-safe in concurrent situations

77. What is ThreadLocal? What are the usage scenarios?

ThreadLocal Is a local thread copy variable tool class,
In each thread creates a ThreadLocalMap object,
simply say ThreadLocal It's a way of exchanging space for time.
Each thread can access its own internal ThreadLocalMap within the object value. 
In this way, resource sharing among multiple threads is avoided.

Principle: Thread-local variables are variables limited to the inside of the thread.
Belongs to the thread itself and is not shared among multiple threads
Java supply ThreadLocal Classes to support thread-local variables are a thread-safe way.
But in a managed environment (such as web server) be careful when using thread-local variables,
In this case, the worker thread outlives any application variables.
Any thread-local variables once not deallocated after the work is done, Java There is a risk of memory leaks in the application.

The classic usage scenario is to assign each thread a JDBC connect Connection. 
This ensures that each thread is in its own Connection Perform database operations on
 won't appear A thread off B thread is still in use Connection
 besides Session management issues.

78. Please talk about how ThreadLocal solves concurrency security?

exist Java In programs, two commonly used mechanisms are used to solve multi-threaded concurrency problems.
one is synchronized way, through the locking mechanism,
When one thread executes, another thread waits, which is to allow multiple threads to execute serially in a way of exchanging time for space.
And another way is ThreadLocal Way,
By creating thread local variables, multiple threads can be executed in parallel by exchanging space for time.

The two methods have their own advantages and disadvantages, are applicable to different scenarios, and should be selected according to different business scenarios.

exist Spring In the source code, it is used ThreadLocal to manage connections,
In many open source projects, it is often used ThreadLocal To control multi-threaded concurrency issues,
Because it's simple enough, we don't need to care about thread safety issues,
Because variables are unique to each thread.

79. Many people say that ThreadLocal should be used with caution. Tell me about your understanding. What should you pay attention to when using ThreadLocal?

ThreadLocal Variables solve the problem of sharing variables in a single thread in a multi-threaded environment.
use the name ThreadLocalMap The hash table is maintained
key for ThreadLocal variable name, value for ThreadLocal the value of the variable

The following points should be paid attention to when using:
1.between threads threadLocal Variables are local variables and do not affect each other
2.use private final static Modifications to prevent memory leaks in multiple instances
3.After being used in the thread pool environment, the threadLocal variable remove()drop or set to an initial value

80. Why is the code reordered?

When executing a program, in order to improve performance, processors and compilers often reorder instructions,
But you can't reorder at will, not how you want to sort, how to sort,

Instruction reordering needs to meet the following two conditions:
1.In a single-threaded environment, the results of program execution cannot be changed
2.Reordering not allowed with data dependencies

have to be aware of is:
Reordering will not affect the execution results in a single-threaded environment, but it will break the execution semantics of multi-threaded.

81. What is spin?

a lot of synchronized The code inside is just some very simple code, the execution time is very fast,
At this time, locking all waiting threads may be an unworthy operation.
Because thread blocking involves switching between user mode and kernel mode.
now that synchronized The code inside executes very fast,
May wish to let the thread waiting for the lock not be blocked, but in the synchronized the boundaries of doing busy loops,
That's spin.
If you have done multiple loops and found that the lock has not been acquired,
Then blocking, this may be a better strategy.

82. What is the principle of synchronized lock upgrade in multithreading?

synchronized Lock upgrade principle:
In the object header of the lock object there is a threadId field,
on first visit threadId Is empty, JVM Let it hold a biased lock,
and put the object header inside the threadId set to the current thread's id,
Will judge when re-entering threadId Is it with its thread id consistent,
If it is consistent, you can use this object directly,
If inconsistent, upgrade the biased lock to a lightweight lock,
Acquire the lock by spinning a certain number of times,
After a certain number of executions, if the object to be used has not been obtained normally,
At this time, the lock will be upgraded from a lightweight lock to a heavyweight lock.
This process constitutes synchronized lock upgrade

The purpose of lock escalation: lock escalation is to reduce the performance consumption caused by locks.
exist Java6 post-optimization synchronized way of realization,
Using the method of upgrading the biased lock to a lightweight lock and then to a heavyweight lock,
Thereby reducing the performance consumption caused by the lock.

83. What is the difference between synchronized and ReentrantLock?

synchronized yes and if,else,for,while same keyword
ReentrantLock is class
 This is the essential difference between the two.
now that ReentrantLock is a class, then it provides more than synchronized More and more flexible features,
Can be inherited, can have methods, can have various variables

synchronized The early implementation is relatively inefficient, compared to ReentrantLock,
The performance of most scenarios is quite different,
But when Java6 middle pair synchronized Made a lot of improvements

The same point: both are reentrant locks

The concept of reentrant lock is: you can acquire your own internal lock again
 For example, a thread acquires a lock on an object, but the object lock has not been released yet.
When you want to acquire the lock of this object again, you can still acquire it.
If it is a non-reentrant lock, it will cause a deadlock.
Every time the same thread acquires a lock, the lock counter is incremented by 1.
So the lock cannot be released until the lock counter drops to 0.

The main differences are as follows:
1.ReentrantLock It is more flexible to use, but there must be a cooperative action to release the lock
2.ReentrantLock Locks must be acquired and released manually, whereas synchronized No need to manually release and unlock the lock
3.ReentrantLock Only applies to code block locks, while synchronized You can modify classes, methods, variables, etc.
4.The locking mechanism of the two is actually different.
ReentrantLock The underlying call is Unsafe of park()method locking
synchronized The operation should be in the object header mark word

Java Each object in can be used as a lock, which is synchronized The basis for achieving synchronization:
1.Ordinary synchronization method, the lock is the current instance object
2.Static synchronization method, the lock is the current class class object
3.Synchronized method block, the lock is the object in the brackets

84. What is the Lock interface (Lock Interface) in the Java Concurrency API? What are its advantages over synchronous?

Lock Interfaces provide more scalable operations than synchronized methods and synchronized code blocks.
They allow for a more flexible structure, can have completely different properties, and can support condition objects of multiple related classes

Lock The advantages of the interface are:
1.can make locks fairer
2.Allows threads to respond to interrupts while waiting for a lock
3.You can let the thread try to acquire the lock, and return immediately or wait for a period of time when the lock cannot be acquired
4.Locks can be acquired and released at different scopes and in different orders

overall Lock yes synchronized expansion board,
Lock provides an unconditional, pollable ( tryLock()method), timed ( tryLock(parameter)method with parameters),
Interruptible ( lockInterruptibly()method), multi-condition queue(newCondition()method)lock operation.
in addition Lock The implementation classes basically support unfair locks (default) and fair locks.
synchronized Only unfair locks are supported,
Of course, in most cases, unfair locks are an efficient choice.

Tags: Java Front-end servlet

Posted by phpcip28 on Mon, 27 Mar 2023 03:12:57 +0530