"ls" in a container within a volume shared with Windows host gets stuck when there are many files in a directory

Background

I am running a Spring Boot application in a docker container (Ubuntu image).
The code is written in Kotlin and it walks through a directory on disk that contains 300,000 files.
I run the following code:

  File(dir)
    .walk()
    .forEach{logger.info("{}", it.name)}

and this code blocks for at least 10 minutes.

I would expect that lines should start being printed very shortly after invoking walk.
Indeed the code works as expected when running it from Intellij – that is, not in a container.

Question:

Why is this happening and how can I fix it?


What I Have Tried

First Trial

I have tried just calling File.listfiles and logging the number of files like so:

   val count = File(dir).listFiles().size
   logger.info("{}", count)

This also blocked for a very long time and eventually logged the value 0.

Second Trial

I changed the settings for Docker Desktop.
I increased the RAM to 20 GB and the swap file to to 1 GB
This had no effect on the result.

Source: StackOverflow