Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread 1 is executing in java synchronized method 1, can Thread 2 then execute in java synchronised method 2?

Was wondering if someone could help clear this up for me. (Student)

Say we have two threads, "Thread1" & "Thread2". If Thread1 is executing in method 1 can Thread2 then execute in method2?

void method1() {
    synchronized (this) {
    }
}

void method2() {
    synchronized (this) {
    }
}

I'm either thinking yes, Thread2 can enter as "this" is just the instance of that method or no because "this" is the instance of that class and Thread1 holds onto it.

like image 507
Kevvvvyp Avatar asked May 20 '14 14:05

Kevvvvyp


1 Answers

There isn't a monitor associated with a specific method - there's a monitor associated with an object. So if you're trying to synchronize on the same object in both methods, the second thread will block until the first thread releases the monitor.

(Personally I don't like synchronizing on this anyway - I synchronize on a reference to an object that only my class has access to. But that's a different matter.)

like image 103
Jon Skeet Avatar answered Oct 31 '22 20:10

Jon Skeet