alex suhaiö alex suhaiö - 3 months ago 18
Java Question

Two threads and two CPU

I have some struggle to understand the following situation:
(i am working in java)
Let's say, we have an object o , two different threads t1 and t2 and two CPU.
if t1 calls o.method1 and t2 calls the o.method2 at the same time, can cpu1 run o.method1 and cpu2 o.method2 at the same time?

Answer

Yes, it can. However, nothing guarantees you that different threads are actually executed in parallel. You only have a guarantee that they are executed concurrently.

The operating system is free to bind your threads to one CPU (and even switch the CPUs of threads). This is done all the time.

In particular, when other applications are running CPU-intensive computations, your two threads may share the same CPU. In this case, your threads run interleaved.

(In this answer, what I said about CPU also applies to CPU cores.)

Of course, locks and synchronization can make one thread wait on the other. Still technically, this waiting can be interpreted as running, although it is not consuming CPU time.

Also note that executing methods in parallel (usually) has nothing to do on which objects you call methods. In your example, you are calling two different methods on the same object. However, this is completely irrelevant. Except if both methods are markes as synchronized in Java, which introduces a synchronization (see paragraph above) on this particular object and make one thread wait until the other has finished its call on that method.