Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breakpoint hits Hashmap.put() a simple Hello World Program

Program is simple:

public class HelloWorld {
    public static void main(String args[]){
       System.out.println("Hello World");
    }
}

Now I set a breakpoint into function put(K key, V value) in HashMap.class

public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);

and then I start debugging the HelloWorld.class, it will run into the breakpoint in HashMap. It is strange to me that how it can run into put() in HashMap?
I tried HashMap, Hashtable and they are all the same.

like image 998
Flory Li Avatar asked Dec 06 '15 12:12

Flory Li


3 Answers

Here is the stack trace I obtained when reproducing your scenario.

When the application is started by Eclipse, it does not simply enter the Main function. Your class needs to be loaded into the JVM, before creating an instance. For that, a Class Loader will be used.

In your case, URLClassLoader has a member of URLClassPath type that uses a HashMap object.

enter image description here

like image 136
VAndrei Avatar answered Nov 13 '22 01:11

VAndrei


It is because of the way Eclipse launches applications.

Eclipse LauncherHelper class running the app (HelloWorld) invokes a URLClassLoader, and tons of other things. The URLClassLoader uses HashMaps, HashTables, etc.

like image 30
Gergely Bacso Avatar answered Nov 13 '22 01:11

Gergely Bacso


Since you're already using a Debugger you should also able to see the frames which show where your put method was called. In IntelliJ it looks like this:

frames

As you can see here, the method was called when the JVM tries to load a certain class: here it is your HelloWorld class. It does that to call the main method in there.

Since the JVM has just started it needs to fill a certain HashMap<String, URLClassPath.Loader> lmap in the sun.misc.URLClassPath class. This map contains entries to used resources like used jar files (for example the jar files from the Java installation) or .class locations like your "bin" directory of your project. It will then be used during the runtime of your application.

But a Map will also be used, then the JVM loads the "permissions" in java.security.Permissions which has Map<Class<?>, PermissionCollection> permsMap.

As you can see, the call of the put method has nothing to do with the content of your own application. It is just used to load basic stuff for the Java environment and the application runtime.

Btw: try to get familiar with your debugger, it will help you to understand why certain methods get called and which class/method performs that call.

like image 35
Tom Avatar answered Nov 12 '22 23:11

Tom