0

For example if I use dual core processor and write a java program without using threads. Does it mean the program execution is sequential and it will only use single core among the dual?


For example if I use dual core processor and write a java program using threads and synchronisation. Does it mean the program execution is parallel and it will use all available cores(in this case two cores)?

If my reasoning is totally wrong then , what is the relation between threading,cores and parallelism?

Gray
  • 115,027
  • 24
  • 293
  • 354
udi
  • 501
  • 2
  • 8
  • 14

1 Answers1

2

First, the JVM has a number of background threads that will use multiple CPUs and cores even if the user code never forks another thread. The garbage collector for example will run concurrently in another CPU if possible regardless of the user code.

If your user code never forks another thread, the JVM will never run your code concurrently in multiple CPUs. If you do write your program with multiple threads there is no guarantee that it will be run in multiple CPUs but it is certainly more likely. It depends a lot on what else is running on on the OS and how blocked your threads are. If you threads are consuming a lot of CPU cycles and run for any length of time on a modern OS then yes, your program will use both CPUs.

You can verify this on a Linux OS (and other Unixen) by watching to see if your process consumes more than 100% of CPU at any one time. You can also use ps options to show the underlying threads and their CPU usage. See my answer here: Concurrency of posix threads in multiprocessor machine

Community
  • 1
  • 1
Gray
  • 115,027
  • 24
  • 293
  • 354
  • Thank you for your explanation. If JVM is responsible for using multiple cores why it is told , Scala supports parallel processing but java not? by the way both are using JVM. Please clarify me. – udi Nov 07 '12 at 05:37
  • Can you provide the quote please @udi? I've written many high performance Java programs. If anyone says that Java doesn't use multiple threads is dead wrong. Java has used the JVM much longer than Scala. :-) – Gray Nov 07 '12 at 05:40
  • Sorry I misinterpreted. Java supports parallel processing by using threads and synchronisation. But Scala using it Implicitly. If you find some free time please watch this video http://www.youtube.com/watch?v=3jg1AheF4n0 and clarify my doubt . This is speech by Martin creator of Scala. – udi Nov 07 '12 at 07:02
  • 1
    Scala has a ton more language features that allow for parallelization and concurrency but I don't believe it also will run your programs in multiple CPUs without you indicating .par collections or using the concurrent language features @udi. – Gray Nov 07 '12 at 15:09