Q1: What are the problems with using HashMap in a multi-threaded environment? Under what circumstances does using the get() method create an infinite loop? There is nothing wrong with HashMap, depending on how you use it. For example, if you initialize a HashMap in one thread and then read it in multiple other threads, there’s absolutely nothing wrong with that. One example is the use of HashMap to store system configuration items. The real problem comes when more than one thread changes the HashMap, such as adding, deleting, or updating key-value pairs. Because a put() operation can re-sizeing the storage, it is possible to create an infinite loop, so use Hashtable or ConcurrentHashMap, which is preferable.

Question 2: Does not overwriting the Bean’s hashCode() method have any performance impact? This is a very good question and everyone will probably have their own experience. From what I know, if a method of calculating a hash is poorly written, the direct effect is that adding elements to the HashMap causes more frequent collisions, thus ultimately increasing the elapsed time. Since Java 8, however, this effect is not as significant as it was in previous versions, because when conflicts occur beyond a certain point, the implementation of the linked list class is replaced by a binary tree implementation, and you still get O(logN) overhead, which is better than O(n) overhead of the linked list class.

Question 3: For an immutable class, must every object in it be declared final? Not really, because you can change a member by declaring it non-final and private, and not in other places than the constructor. Do not provide setter methods for them and do not leak references to this member through any function. Keep in mind that declaring an object final only guarantees that it will not be reassigned another value. You can still modify the properties of the referenced object through this reference. This is key, and interviewers usually like to hear you emphasize it.

How is the substring() method of String implemented internally? Another good Java interview question, you should answer “the substring method creates a new object from the original string”, otherwise your answer will not be satisfactory. This question is also often used to test candidates’ knowledge of the potential memory leak risks associated with substring(). Until Java version 1.7, subString kept a reference to the character array of the original string, which meant that if you intercepted five characters from a 1GB string, those five characters would prevent that 1GB from being reclaimed because the reference was a strong reference.

In Java 1.7, this problem was fixed and the character array of the original string was no longer referenced, but the change also made the creation of the string by subString () much more time-consuming, with overhead previously O(1) and now O(n) at worst.

Question 5: Can I write a singleton pattern and guarantee the uniqueness of instances? This is one of the core Java questions, and the interviewer expects you to know that you should double-check the initialization of instances when writing singletons. Remember to use the Volatile keyword for instance declarations to keep the singleton thread-safe. Here is an example that shows how the singleton pattern can be implemented in a thread-safe way:

public class Singleton {

private static volatile Singleton _instance;

/**
 * Double checked locking code on Singleton
 * @return Singelton instance
 */
public static Singleton getInstance() {
    if (_instance == null) {
        synchronized (Singleton.class) {
            if (_instance == null) {
                _instance = new Singleton();
            }
        }
    }
    return _instance;
}
Copy the code

} Q6: How do you handle error situations when writing stored procedures or calling stored procedures in Java? This is a tricky Java interview question, and the answer is fluid. My answer is, when writing a stored procedure, always return an error code whenever an operation fails. But catching a SQLException is the only thing you can do if something goes wrong while calling a stored procedure.

Question 7: What is the difference between the methods executor.submit () and executor.execute ()? This question comes from another article, the 15 Most Popular Java Multithreading Interview Questions, and it’s getting more and more attention because of the growing demand for developers with concurrent skills. The answer is: the former returns a Future object that can be used to retrieve the results of worker thread execution.

Another difference occurs when we look at exception handling. When you use execute to throw an exception, it will be handled by an uncaught exception handler. If you do not explicitly specify an exception handler, by default it will simply print an error stack through system. err. When you submit a task with Submit, if the task throws an exception (whether or not it is run time), that exception is part of the object returned by the task. In this case, when you call the future.get () method, the method rethrows the exception and wraps it with ExecutionException.

Q8: What is the difference between the factory pattern and the abstract factory pattern? The Abstract factory pattern provides multiple levels of abstraction. Different factory classes inherit from the same abstract factory method, but create different objects based on the class of the factory. For example, AutomobileFactory, UserFactory, and RoleFactory all inherit AbstractFactory, but each factory class creates its own object of the corresponding type. The following is a UML diagram of the factory pattern and the abstract factory pattern.

What is the singleton pattern? When creating a singleton, is it better to mark the entire method as synchronized or just the statement created as synchronized? In Java, singleton classes are classes that have only one instance in the entire Java program, such as java.lang.Runtime. Creating singleton cases was a bit of a hassle in Java version 4 and before, but things have become easier since Java 5 introduced the Enum type. Check out my article on how to create singleton classes using enums, and take a look at Question 5 to see how to double check when creating singleton classes.

Can I write code that iterates through a HashMap using Java 4 or 5? In fact, there are four ways to iterate over any Map in Java. One is to get all the keys using the keySet() method, then iterate over the keys, and then get the corresponding values using the get() method. The second method uses entrySet() to retrieve a collection of key-value pairs, and then uses the for each statement to iterate over the collection, each of which already contains the key and value. This is a better way to do it because you get both the key and the value in each iteration without calling the get() method, which has O(n) performance overhead if the bucket location has a huge list. The third method is to get an entrySet and then use the iterator to get each key-value pair in turn. The fourth method is to get the key set and use the iterator to get each key in turn and then call the get method based on the key.

11. When do you override hashCode() and equals()? You need to rewrite these functions when you need to make equality judgments based on business logic rather than object equality. For example, two Employee objects are equal based on the fact that they have the same EMP_id, even though they could be two different Object objects created in different places. Also, you’ll have to override these methods if you’re going to use them as keys in a HashMap. Now, as an equal-Hashcode convention in Java, when you override equals you must also override hashCode, otherwise you break the convention that sets such as sets, maps, etc. depend on to function properly. You can check out another of my posts to understand the subtle differences and connections between these two approaches.

12. What happens if you don’t override the hashCode method? The convention between equals and hashCode is broken if the equals method is not overridden: When two objects are returned equal through equals, their hashCode must be the same, too. If you don’t override hashCode, even two objects that return true using equals will still be inserted into two different locations when they are inserted into the same map because hashCode returns different values. This defeats the purpose of a HashMap, since the Map itself does not allow storing the same value for two keys. When inserting an object using the PUT method, the HashMap calculates the object’s Hashcode, finds the bucket based on it, and then iterates through all the Map.Entry objects at the bucket to see if they are the same as the object to be inserted. None of this would be possible without providing hashCode.

Q13: Do we synchronize the entire getInstance() method, or just the key parts of the getInstance() method? The answer is: synchronize only the Critical sections. This is because, if we synchronized the entire method, every time a thread called getInstance(), it would wait for another thread to complete, even though no object creation was performed in the method. In other words, we only need to synchronize the code that creates the object, and the code that creates the object only executes once. Once the object is created, there is no need to synchronize methods. In fact, in terms of performance, synchronizing method protection is a killer encoding method, because it degrades performance by a factor of 10 to 20. The following is a UML diagram of the singleton pattern.

As a side note, there are several ways to create thread-safe singletons, which you can also mention in passing.

Q14: what do equals() and hashCode() do when calling get() on HashMap? This question is a supplement to Q12, but candidates should be aware that once you mention the hashCode() method, people will probably ask how HashMap uses this function. When you insert a key into a HashMap, first the object’s hashCode() method is called, and the result is used to calculate the bucket to be stored.

Because a location may already contain multiple Map.entry objects in a linked list, HashMap uses the equals() method to compare this object to all the keys contained in map.Entry to determine if the key object already exists.

How do I avoid deadlocks in Java? You can avoid deadlocks by breaking situations where you have to wait for each other. To do this, you need to arrange the lock acquisition and release sequence in your code. If the order in which locks are acquired is fixed and the order in which they are acquired is reversed from the order in which they are released, deadlock conditions will not occur.

What is the difference between using literals and using the new String() constructor when creating String objects? When we use the New String constructor to create a String, the value of the String is created in the heap and not added to the JVM’s String pool. Instead, strings created with literals are placed in the PermGen segment of the heap. Such as:

String STR = new String (” Test “); The object STR created by this code will not be put into the String pool; we need to explicitly call the String.intern() method to put it into the String pool. Java automatically puts a String into a String pool only if you create it with a literal, such as String s= “Test”. Incidentally, it’s easy to overlook that when we pass the parameter “Test” to the constructor, the parameter is a literal value, so it will also hold another copy in the string pool. To learn more about the difference between literal strings and string objects, see this article.

The following chart nicely illustrates this difference.

17. What is an Immutable Object? Can you write an example? Immutable objects are those that cannot be modified once created. Any changes to this object result in the creation of a new object, rather than making changes to the original object itself. The String class in Java, for example, is immutable. Most of these classes are usually final because they avoid being inherited and then overwritten, in which immutable properties are not guaranteed. You can usually get the same effect by making class members private but non-final.

In addition, you also want to ensure that your class does not expose members through any methods, especially those of modifiable types. Similarly, when your method receives a modifiable object from a client class, you should use a duplicate object to prevent the client code from modifying the modifiable object just passed in. For example, if you pass in a java.util.date object, you should use the clone() method to get a copy yourself.

When you return a modifiable object via a class function, you take a similar precaution by returning a copy of the class’s success, preventing client code from modifying the properties of the member object via the reference. Never return your modifiable members directly to the client code.

Question 18: How to calculate the execution time of a method in the simplest way without using any analysis tools? Take a system time before and after executing the method, and take the difference between the two times to get the time taken by the method.

Note that if this method takes a very short time to execute, the resulting time value might be 0ms. At this point you can try the effect on a more computationally intensive method.

long start=System.currentTimeMillis();

method();

long end=System.currentTimeMillis();

System.out.println(“Time taken for execution is “+(end-start)); 19. What two methods do you need to override when using a class as the key of a HashMap? In order for a class to be used as a key in a HashMap or Hashtable, the class must implement its own equals() and hashCode() methods. For details, see Question 14.

Q20: How do you prevent client code from directly initializing your class’s constructor? For example, if you have an interface called Cache and two concrete implementation classes MemoryCache and DiskCache, how do you ensure that these two classes prohibit client code from fetching instances of them using the new keyword?

If you want to learn Java engineering, high performance and distributed, simple. Micro services, Spring, MyBatis, Netty source analysis of friends can add my Java advanced group: 617434785, group ali Daniel live explain technology, as well as Java large Internet technology video free to share to you.