20 Java-side questions from investment banks

Source: Internet
Author: User

question one: What's wrong with using HashMap in a multithreaded environment? Under what circumstances does the get () method produce an infinite loop? There is no problem with HashMap itself, and there is no problem depending on how you use it. For example, if you initialize a hashmap in a thread and then read it on multiple other lines thread, there's definitely no problem. One example is the use of HashMap to store system configuration items. When there are more than one thread modifying the HashMap, the problem will actually arise, such as adding, deleting, and updating key-value pairs. Because the put () operation can cause an action to reallocate the storage size (re-sizeing), it is possible to cause an infinite loop to occur, so you need to use Hashtable or CONCURRENTHASHMAP, which is better. question two: Does overwriting the Bean's Hashcode () method affect performance? This problem is very good, everyone may have their own experience. As far as my knowledge is concerned, if a hash method is poorly written, the direct effect is that when adding elements to the hashmap, it will cause more frequent collisions and thus eventually add time. But since the beginning of Java 8, this effect is no longer as significant as the previous versions, because when the conflict occurs beyond a certain limit, the implementation of the list class will be replaced with a binary tree implementation, you can still get O (logn) cost, better than the list class O (n). question three: For a class that cannot be modified, does each of its objects have to be declared as final?

Not necessarily, because you can declare a member to be non-final and private, and not modify it anywhere but the constructor. Do not provide a setter method for them, and do not disclose a reference to this member through any function. It is worth remembering that declaring an object as final only guarantees that it will not be re-assigned to another value, and that you can still modify the properties of the referenced object by this reference. This is key, and interviewers usually like to hear you emphasize this point.

Question four: How is the substring () method of string implemented internally?

Another good question for the Java interview, you should answer the "substring method to create a new object through the original string", otherwise your answer is certainly not satisfactory. This problem is also often tested to see if the candidate is aware of the potential memory leak risks that substring () might bring. Until Java 1.7, substring will save a reference to the character array of the original string, which means that if you intercept 5 characters from a 1GB size string, these 5 characters will prevent the 1GB memory from being recycled because the reference is a strong reference.

To Java 1.7, this problem is resolved, the original string character array is no longer referenced, but this change also makes substring () create the string operation more time-consuming, the previous overhead is O (1), and now the worst case is O (n).

question five: Can you write a singleton pattern and guarantee the uniqueness of the instance?

This is one of the core issues of Java, the interviewer expects you to know that when you write a singleton pattern, you should double-check the initialization of the instance. Remember to use the volatile keyword for the declaration of the instance to ensure that the singleton mode is thread safe. Here is an example of how to implement a singleton pattern 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;

}

}

Question six: How do you handle error situations when you write a stored procedure or call a stored procedure in Java?

This is a tricky Java interview question, and the answer is not fixed. My answer is that when you write a stored procedure, you must return an error code once the operation fails. But when it comes to calling the stored procedure, capturing SqlException is the only thing that can be done.

Question seven: What is the difference between the two methods of Executor.submit () and Executor.execute ()?

This issue comes from another article, "15 Most popular Java multi-threaded interview problem", and now the need to master the concurrency skills of developers more and more, so this issue is increasingly attracting attention. The answer is: The former returns a future object that can be used to obtain the results of the worker thread execution.

When we examine the handling of exceptions, we find another difference. When you throw an exception with the task submitted by execute, this exception is handled by the unhandled exception handling process (Uncaught exception handler), when you do not explicitly specify an exception handler, By default, the error stack is printed only by System.err. When you submit a task with submit, the task throws an exception (regardless of whether it is a run-time exception), and the exception is part of the task's return object. In such a case, when you call the Future.get () method, this method will re-throw the exception and will be wrapped using executionexception.

question eight: What is the difference between Factory mode and abstract Factory mode?

Abstract Factory mode provides a multi-level abstraction. Different factory classes inherit the same abstract factory method, but create different objects based on the factory's category. For example, Automobilefactory, Userfactory, and rolefactory all inherit abstractfactory, but each factory class creates its own object of the corresponding type. The following is the UML diagram for the Factory mode and the abstract Factory mode.

question nine: What is a singleton mode? When you create a singleton object, you mark the entire method as synchronized good or just mark the created statement as synchronized good?

In Java, a singleton class refers to a class that has only one instance of the entire Java program, such as Java.lang.Runtime, which is a singleton class. It's a bit of a hassle to create a single session in Java version 4 and before, but since Java 5 introduced the enum type, things have become simpler. You can go and see my article on how to use enum to create a singleton class, and then look at the question Friday to see how to double check when creating a singleton class.

Question 10: Can I write a code that iterates through a hashmap with Java 4 or 5来?

In fact, there are four ways to traverse any map in Java, one is to use the keyset () method to get all the keys, then traverse the keys, and then get the corresponding values by using the Get () method. The second method can use EntrySet () to get a collection of key-value pairs, and then use the for every statement to iterate over the collection, and each key-value pair that is obtained when it is traversed already contains the key and value. This is a better way to do this, as each round of traversal has both a key and value, no need to call the Get () method, and the Get () method is O (n) when the bucket position has a huge list. The third method is to get entryset and then use iterator to get each key-value pair in turn. The fourth method is to get the key set and then use iterator to get each key sequentially, and then call the Get method based on key.

Question 11: When do you rewrite the hashcode () and Equals () methods?

You need to rewrite these two functions when you need to judge by the business logic for equality, rather than judging by the equality of objects. For example, two employee objects are equal because they have the same emp_id, although they may be two different object objects and are created in different places, respectively. Also, if you are going to use them as keys in HashMap, you must also rewrite both methods. Now, as a convention for Equals-hashcode in Java, you must also rewrite hashcode when you rewrite equals, or you will break the conventions on which set, map, and so on work. You can look at one of my other blog posts to understand the subtle differences and linkages between the two approaches.

12: What is the problem if I don't rewrite the Hashcode method?

If you do not override the Equals method, the contract between equals and Hashcode is broken: When you return an equal two objects by using the Equals method, their hashcode must be the same. If you do not override the Hashcode method, even if you use the Equals method to return two objects with a value of true, when they are inserted into the same map, they will still be inserted into two different positions because hashcode returns different. This breaks the original purpose of HashMap because the map itself does not allow two keys to be stored in the same value. When a put method is used to insert a, HashMap calculates the object's hashcode, then finds the storage location (bucket) based on it, and then iterates through all the Map.entry objects on that storage location to see if the object is the same as the one being inserted. None of this would have been possible without the provision of hashcode.

Question 13: Do we synchronize the entire getinstance () method or just the key part of the getinstance () method?

The answer is: Just sync the key parts (Critical section). This is because, if we synchronize the entire method, each time the thread calls the GetInstance () method, it waits for the other threads to call to finish, even if the object creation operation is not performed in this method. In other words, we just need to synchronize the code that creates the object, and the code that creates the object executes only once. Once the object is created, there is no need to synchronously protect the method at all. In fact, in terms of performance, synchronous protection of the method is very deadly, because it reduces performance by 10 to 20 times times. The following is a UML diagram of a singleton pattern.

To add, there are a number of ways to create a thread-safe singleton, which you can also mention by the way.

question 14: HashMap, what does the Equals () and Hashcode () methods do when the Get () method is called?

This question is a supplement to question 12, and the candidate should know that once you mention the Hashcode () method, it is likely to be asked how HashMap uses the function. When you insert a key into the HashMap, first, the object's Hashcode () method is called, and the result is used to calculate where the bucket will be stored.

Because more than one Map.entry object might already be contained in a linked list in a location, HashMap uses the Equals () method to compare this object to the key contained by all of these map.entry to determine if the key object already exists.

question 15: How do I avoid deadlocks in Java?

You can avoid deadlocks by breaking the waiting situation. To achieve this, you need to reasonably arrange the order in which to get and release locks in your code. If the order in which the locks are obtained is fixed, and the order in which they are obtained is exactly the opposite of the order of release, there will be no deadlock condition.

question 16: When creating a String object, what is the difference between using literals and using the new string () constructor?

When we use the new string constructor to create a string, the value of the string is created in the heap instead of being joined to the JVM's string pool. Instead, a string object created with literal values is placed in the PermGen segment of the heap. For example:

String Str=new string ("Test");

This code creates the object str is not placed in the string pool, we need to explicitly call the String.intern () method to put it into the string pool. Only when you create a string with literal values does Java automatically put it into a string pool, such as String s= "Test". By the way, there's an easy place to overlook, and when we pass the parameter "Test" to the constructor, this parameter is a literal value, so it also saves another copy in the string pool. To learn more about the difference between a literal string and a string object, see this article.

This difference is well explained.

question 17: What are non-modifiable objects (immutable object)? Can you write an example?

Non-modifiable objects are those that cannot be modified once they are created. Any change to this object would result in a new object being created, rather than being modified in the original object itself. For example, the string class in Java is non-modifiable. Most of these classes are usually final type, because this avoids being inherited and then overridden, and in the overridden method, the non-modifiable features are difficult to secure. You can usually get the same effect by setting the members of the class to private but not final.

In addition, you should also ensure that your class does not expose members in any way, especially those that can modify the type. Similarly, when your method receives incoming modifiable objects from the client class, you should use a replicated object to prevent the client code from modifying the newly-passed modifiable class. 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 through a class function, you also take similar precautions to return a successful copy of a class that prevents the client code from modifying the properties of the member object through this reference. Never directly return your modifiable members to the customer code.

question 18: How long does it take to calculate the execution of a method in the simplest way without using any analysis tools? Before and after executing this method, get a system time, take the difference between these two times, you can get the time that this method takes.

It is important to note that if the time taken to execute this method is very short, then the resulting time value may be 0ms. At this point you can try the effect on a method with a larger amount of computation.

Long Start=system.currenttimemillis ();

Method ();

Long End=system.currenttimemillis ();

System.out.println ("Time Taken for execution" + (End-start));

question 19: When you want to use a class as HashMap key, you need to rewrite which of the two methods of this class? In order for a class to be used as a key in HashMap or Hashtable, it is necessary to implement this class's own equals () and Hashcode () methods. Please refer to question 14 for details.

question 20: How do you prevent client code from initializing your class's constructor directly? For example, you have an interface named cache and two specific implementation classes MemoryCache and DiskCache, how do you ensure that these two classes prohibit client code from getting their instances with the New keyword?

I leave this last question to you for practice, and you can think it over before I give you the answer. I'm sure you can find the right way, because it's an important way to take control of your class's implementation, and it can provide great benefits for future maintenance.

20 Java-side questions from investment banks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.