Reputation: 15113
I'm replicate to duplicate an exception
in non thread safe code so that it would in infinite loop at findEntry0
while loop
so I created this code:
val map = mutable.Map[Int, String]()
val rand = new Random()
def nextInt() = rand.nextInt(1000000)
for (i <- 1 to 1000) {
new Thread(new Runnable {
def run(): Unit = {
while (true) {
val key = nextInt()
map.put(key, "some string")
map.contains(key)
println(s"thread ${System.currentTimeMillis()} ${Thread.currentThread().getName}")
}
}
}).start()
}
Thread.sleep(120000)
it prints:
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
as you can see it looks like the threads are running sequentially
and not in parallel by the timestamps, am i doing something wrong? how can I get them to run actually concurrently?
am i doing something wrong? i want the threads to run concurrently.
Upvotes: 1
Views: 64
Reputation: 6385
Your sample is not very reliable. Actually it's happening what you expect.
Threads are executed in parallel on your machine. But actually you have limited amount of processors/cores so current context is switching between 1000
threads you've created each and every X ms. Obviously before context switch from one thread to another couple of lines where able to be written.
What I would suggest you - is to mimimize amount of parallel threads to some countable amounts and also add 10ms
sleep inside your infinite loop.
This allow you to see diversity of how all threads works concurrently.
thread 1455123868703 Thread-3
thread 1455123868703 Thread-6
thread 1455123868703 Thread-9
thread 1455123868703 Thread-8
thread 1455123868703 Thread-2
thread 1455123868703 Thread-7
thread 1455123868721 Thread-9
thread 1455123868721 Thread-2
thread 1455123868721 Thread-4
thread 1455123868721 Thread-5
thread 1455123868721 Thread-6
thread 1455123868721 Thread-8
thread 1455123868721 Thread-3
thread 1455123868721 Thread-7
thread 1455123868721 Thread-0
thread 1455123868721 Thread-1
Upvotes: 2