1. The equals method is used to compare whether the content of the object is equal (overridden later)
2. Hashcode method is only used in collections
3. When the equals method is overwritten, whether the comparison object is equal will be compared through the overwritten equals method (judging whether the contents of the object are equal).
4. When putting an object into a collection, first determine whether the hashcode value of the object to be placed into is equal to the hashcode value of any element in the collection. If it is not equal, put the object into the collection directly. If the hashcode values are equal, then use the equals method to determine whether the object to be placed is equal to any object in the collection. If the equals judgment is not equal, put the element directly into the collection, otherwise it will not be placed.
5. The equals method uses whether the object memory addresses are equal to determine whether the objects are equal.
Because they are two new objects, the memory addresses of the objects are not equal, so stu1.equals(stu2) is false.
6. Threads A and B must both obtain the lock of object O. Assuming that A acquires the lock of object O, B will wait for A to release the lock of O. If synchronized is used, if A does not release, B will wait for it to continue and cannot be interrupted. If ReentrantLock is used, if A does not release, B can interrupt the waiting after waiting for a long enough time and do other things.
ReentrantLock acquires locks in three ways:
a) lock(), if the lock is acquired, return immediately. If another thread holds the lock, the current thread will remain in a dormant state until the lock is acquired.
b) tryLock(), if the lock is acquired, it will return true immediately, and if another thread is holding the lock, it will return false immediately;
c) tryLock(long timeout,TimeUnit unit), if the lock is acquired, it will return true immediately. If another thread is holding the lock, it will wait for the given time of the parameter.
During the waiting process, if the lock is acquired, it returns true, and if the waiting timeout, it returns false;
d) lockInterruptibly: If the lock is acquired, return immediately. If the lock is not acquired, the current thread is in a dormant state until or locked.
Or the current thread is interrupted by another thread
Synchronized is implemented at the JVM level. Not only can synchronized lock be monitored through some monitoring tools, but exceptions can also occur during code execution.
The JVM will automatically release the lock, but it is not possible to use Lock. Lock is implemented through code. To ensure that the lock will be released, unLock() must be placed in finally{}
When the resource competition is not very fierce, the performance of Synchronized is better than that of ReetrantLock. However, when the resource competition is very fierce, the performance of Synchronized will decrease by dozens of times, but the performance of ReetrantLock can remain normal;
In the JDK, the following classes are mainly used to implement the Java reflection mechanism, which are all located in the java.lang.reflect package:
Class: represents a class.
Field class: A member variable representing a class (member variables are also called attributes of a class).
Method class: A method representing the class.
Constructor class: represents the constructor method of the class.
Array class: Provides static methods for dynamically creating arrays and accessing elements of the array.
Here are a few examples to see the actual application of the Reflection API:
1. Get member variables, member methods, interfaces, superclasses, constructor methods, etc. through Class class
The getClass() method is defined in the java.lang.Object class, so for any Java object, the object type can be obtained through this method. The Class class is a core class in the Reflection API, and it has the following methods
getName() : Get the full name of the class.
getFields() : Get the property of the public type of the class.
getDeclaredFields() : Get all properties of the class.
getMethods(): A method to obtain the public type of the class.
getDeclaredMethods() : Get all methods of the class.
getMethod(String name, Class[] parameterTypes): Gets a specific method of the class, name parameter specifies the name of the method, parameterTypes parameter specifies the parameter type of the method.
getConstructors(): Get the constructor of the public type of the class.
getConstructor(Class[] parameterTypes): Gets the specific constructor of the class. The parameterTypes parameter specifies the parameter type of the constructor.
newInstance(): Create an object of this class through the class's constructor without parameters.
Steps to write a Java reflector:
1) You must first get the Class object of a class
For example:
Class c1 = Test.class; Class c2 = Class.forName("com.reflection.Test"); Class c3 = new Test().getClass(); 2) Then call the methods in the Class object separately to obtain the properties/methods/constructors of a class
Note: If you want to obtain methods/properties/constructors in the class normally, you should focus on the following reflection classes
Field
Constructor
Method
<servlet-mapping> <servlet-name></servlet-name><url-pattern></url-pattern> </servlet-mapping> for (String elementA:str ) { System.out.print(elementA + " "); } List<String> list = new ArrayList<String>(); for (int i=0; i<str.length; i++) { if(!list.contains(str[i])) { list.add(str[i]); } }Set<String> set = new HashSet<String>(); for (int i=0; i<str.length; i++) { set.add(str[i]); }Spring has six transactions and five isolation levels
Category 1: Inte short int long
Category 2: Float double
The third category: logical boolean (it only has two values that can be deemed true false)
Category 4: Character char
Methods in final modification class
Function: It can be inherited, but it cannot be rewritten after inheritance.
Final modification class
Function: Classes cannot be inherited.
When final modifying the basic type, the value remains unchanged. The reference type indicates that the address remains unchanged. That is, when new, the address cannot be reassigned.
You know the final modification attribute
prepareStatement is precompiled. First submit the SQL to the database for preprocessing, and then put it in the cache. Next time you find that there is the same, you don’t need to compile it. The execution efficiency is high, there are syntax prompts to facilitate checking, and the parameters are dynamic, preventing SQL injection because of syntax checking
select * from tbName = 'zck' and passwd = ' or '1' = '1';
Statement is not precompiled, and requires manual check for syntax errors, which is hardcoded
HashMap allows null as a key or value of an entry, while Hashtable does not
put method
HashMap will perform special processing on the null value key, always put it in the table[0] position. Put the process is to first calculate the hash and then calculate the index value through hash and table.length, and then put the key at the table[index] position. When other elements already exist in table[index], a linked list will be formed at the table[index] position, and the newly added elements will be placed in table[index], and the original elements will be linked through the next of Entry. In this way, the hash conflict problem is solved in the form of a linked list. When the number of elements reaches the critical value (capactiy*factor), the capacity will be expanded, and the length of the table array becomes table.length*2
get method
Similarly, when the key is null, special processing will be performed, and the element with key is null is found on the linked list of table[0].
The process of get is to first calculate the hash and then calculate the index value through hash and table.length, then iterate through the linked list on table[index] until the key is found, and then return the underlying implementation of HashMap and Hashtable are both array + linked list structure implementations to calculate the hash first. The index, which is the subscript of the table array, is calculated based on hash and table.length, is calculated, and the corresponding operation is performed.
Most indexes are based on B-tree
Servlet thread safety issues are mainly caused by instance variables, so instance variables should be avoided in Servlets.
If application design cannot avoid using instance variables, then synchronization is used to protect the instance variables to be used, but for optimal system performance, the code path with minimal availability should be synchronized.
Write a singleton pattern
public static long recursive(int n) {if (n <= 0)return 0;if (n == 1)return 1;return recursive(n - 1) + recursive(n - 2);}public static long loop(int n) {if (n <= 0)return 0;if (n == 1)return 1;long fib1 = 0;long fib2 = 1;long sum = 0;for (int i = 2; i <= n; i++) {sum = fib1 + fib2;fib1 = fib2;fib2 = sum;}return sum;} HashTable is a thread-safe class. It uses synchronized to lock the entire Hash table to achieve thread-safety, that is, lock the entire table every time and let the thread occupy it. ConcurrentHashMap allows multiple modification operations to be performed concurrently, and the key is the use of lock separation technology. It uses multiple locks to control modifications to different parts of the hash table.
ConcurrentHashMap uses segments (Segment) to represent these different parts. Each segment is actually a small Hashtable, and they have their own locks. As long as multiple modification operations occur on different segments, they can be performed concurrently.
Some methods need to cross segments, such as size() and containsValue(). They may need to lock the entire table instead of just a certain segment. This requires locking all segments in sequence. After the operation is completed, the locks of all segments are released in sequence. "In order" is very important here, otherwise there is a high possibility of deadlock. In ConcurrentHashMap, the segment array is final, and its member variables are actually final. However, simply declaring the array as final does not guarantee that the array members are final, which requires implementation guarantees.
This ensures that there is no deadlock, because the order in which the locks are obtained is fixed
① ThreadLocal ② synchronized( ) ③ wait() and notify() ④ volatile
ThreadLocal
ThreadLocal ensures that different threads have different instances, and the same thread must have the same instance, that is, each thread using the variable provides a copy of the value of the variable. Each thread can independently change its own copy, rather than conflict with the copy of other threads.
Advantages: Provides thread-safe shared objects
The difference from other synchronization mechanisms: the synchronization mechanism is to synchronize concurrent access to the same resource by multiple threads, and to communicate between multiple threads;
ThreadLocal is a data sharing that is isolated from multiple threads, and fundamentally does not share resources between multiple threads. This certainly does not require multiple threads to be synchronized.
volatile
The volatile modified member variable is forced to reread the value of the member variable from shared memory each time it is accessed by a thread. and,
When the member variable changes, the thread is forced to write the change value back to shared memory.
Advantages: In this way, at any moment, two different threads always see the same value of a certain member variable.
Reason: The Java language specification states that in order to obtain the best speed, threads are allowed to save private copies of shared member variables.
And it is only compared with the original value of the shared member variable when the thread enters or leaves the synchronous code block.
In this way, when multiple threads interact with an object at the same time, it is necessary to pay attention to allowing the thread to obtain changes in shared member variables in a timely manner.
The volatile keyword prompts the VM: for this member variable, it cannot save its private copy, but should directly interact with the shared member variable.
Usage tips: Use volatile on member variables accessed by two or more threads.
It is not necessary to use when the variable to be accessed is already in the synchronized code block or is a constant.
In order to improve efficiency, a thread copies a member variable (such as A) (such as B), and the access to A in the thread actually accesses B. Synchronization of A and B is only performed in certain actions, so there is a situation where A and B are inconsistent. volatile is used to avoid this situation.
volatile tells jvm that the variables it modifies do not retain copies and directly access the ones in the main memory (it is better to use when there are many read operations; communication is required between threads, but this article cannot do it)
Volatile variables have synchronized visibility properties, but do not have atomic properties.
This means that the thread can automatically discover the latest value of the volatile variable. Volatile variables can be used to provide thread safety, but can only be applied to a very limited set of use cases: there is no constraint between multiple variables or between the current value of a variable and the modified value.
You can only use the volatile variable instead of locks in limited cases. To make the volatile variable ideal thread safety, the following two conditions must be met at the same time:
Write operations to variables do not depend on the current value; the variable is not included in the invariant with other variables.
sleep() vs wait()
sleep is a thread class (Thread), which causes this thread to pause execution for a specified time and send the execution opportunity to other threads, but the monitoring status remains and will automatically resume after that. Calling sleep will not release the object lock.
wait is a method of the Object class. Calling the wait method on this object causes the thread to give up the object lock and enter the waiting lock pool waiting for this object. Only after issuing a notify method (or notifyAll) for this object, this thread enters the object lock pool and prepares to obtain the object lock and enters the running state. (If the variable is declared as volatile, it will be consistent with the main memory every time it is accessed; if the variable is accessed in a synchronous method or synchronous block, the variable is synchronized when the lock is obtained at the entrance of the method or block and the lock is released when the method or block exits.)
http://www.yjbys.com/news/202750.html
The client program needs to obtain a specific container role first, and then obtain a specific iterator role through the specific container role.
Iterator it=new ArrayList.iterator();
1) Access the contents of a container object without exposing its internal representation.
2) Support multiple traversals of container objects.
3) Provide a unified interface (polymorphic iteration) for traversing different container structures.
Use the new keyword} → the constructor was called
Use the newInstance method of the Class class} → the constructor was called
Use the newInstance method of the Constructor class} → the constructor function was called
Using clone method} → No constructor is called
Using deserialization} → No constructor is called
Employee emp2 = (Employee) Class.forName("com.Employee").newInstance(); or
Employee emp2 = Employee.class.newInstance();Constructor constructor = Employee.class.getConstructor(); Employee emp3 = constructor.newInstance();
Using the clone method, we need to first implement the Cloneable interface and implement the clone method defined by it
Employee emp4 = (Employee) emp3.clone();
When the program starts, it does not load all the class files to be used by the program at once. Instead, it dynamically loads a certain class file into memory through the Java class loading mechanism (ClassLoader) according to the needs of the program. Therefore, only after the class file is loaded into memory can it be referenced by other classes. Therefore, ClassLoader is used to dynamically load class files into memory.
Bootstrap ClassLoader: is called the startup class loader, it is the top-level class loader in the Java class loading hierarchy, responsible for loading core class libraries in the JDK, such as: rt.jar, resources.jar, charsets.jar, etc. Extension ClassLoader: is called the extension class loader, responsible for loading Java's extension class library, and loads all jars under JAVA_HOME/jre/lib/ext/ by default.
App ClassLoader: is called a system class loader, which is responsible for loading all jars and class files in the application classpath directory.
Because this can avoid repeated loading, when the father has loaded the class, there is no need for the child ClassLoader to load it again.
Considering security factors, let's imagine that if we do not use this delegate mode, we can dynamically replace the types defined in the Java core API at any time, which will pose a very big security risk. The parent delegate method can avoid this situation, because the String is already loaded by the boot class loader (Bootstrcp ClassLoader) at startup, so the user-defined ClassLoader will never be able to load a String written by itself, unless you change the default algorithm of the ClassLoader search class in JDK.
1. The request object client request, this request will contain parameters from the GET/POST request, and can only understand the customer's needs and then respond.
2. Relevant information about the response object responds to customer requests
3. Session object refers to a session between the client and the server, starting from a WebApplication from the client to the server until the client is disconnected from the server.
4. The out object is an instance of the JspWriter class and is a commonly used object to output content to the client.
5. The page object is pointing to the current JSP page itself, which is a bit like this pointer in the class. It is an instance of the java.lang.Object class
6. The application object realizes the sharing of data between users and can store global variables. It starts with the server startup until the server shuts down
7. Exception object is an exception object. When an exception occurs during the running process, this object is generated.
8. pageContext object provides access to all objects and namespaces in the JSP page
9. The config object is used by the JSP engine to pass information to it when a servlet is initialized.
js has a function isNaN(val)//If it is a number, it returns false
There are XMLDOM parsing, SAX parsing, and StAX parsing
XMLDOM: (XMLDocumentObjectModel) The performance deteriorates greatly when processing large files. This problem is caused by the DOM tree structure, which occupies a lot of memory, and the DOM must load the entire document into memory before parsing the file, which is suitable for random access to XML;
SAX: (SimpleAPIforXML) Unlike DOM, SAX is an event-driven XML parsing method. It reads XML files in sequence and does not require the entire file to be loaded at once. When encountering an event like the beginning of a file, the end of a document, or the beginning of a tag and the end of a tag, it triggers an event where the user processes the XML file by writing processing code in its callback event, suitable for sequential access to XML;
StAX: The difference between (StreamingAPIforXML) and other methods is that applications can handle XML as an event stream, which is better than other methods in terms of performance and availability;
thread.getState()
The above are the Java interview questions compiled by the editor for you. I hope they will be helpful to you. If you have any questions, please leave me a message. The editor will reply to you in time!