June 2018
Intermediate to advanced
310 pages
6h 32m
English
There is a price to pay whenever we create a new thread. Each thread needs a new memory stack.
What if we simulate some work inside each thread by putting it to sleep?
In the following piece of code, we'll attempt to create 10,000 threads, each sleeping for a relatively short period of time:
val counter = AtomicInteger()try { for (i in 0..10_000) { thread { counter.incrementAndGet() Thread.sleep(100) } }} catch (oome: OutOfMemoryError) { println("Spawned ${counter.get()} threads before crashing") System.exit(-42)}
Depending on your operation system, this will result in either OutOfMemoryError or the entire system becoming very slow. Of course, there are ways to limit how many threads are run at once, using the executors ...
Read now
Unlock full access