From the course: Parallel and Concurrent Programming with Java 1

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Synchronized method: Java demo

Synchronized method: Java demo - Java Tutorial

From the course: Parallel and Concurrent Programming with Java 1

Start my 1-month free trial

Synchronized method: Java demo

- [Instructor] Something unique in Java is that every object has an intrinsic lock associated with it, a thread that needs exclusive access to an object's fields has to acquire that object's lock before accessing them and then release that intrinsic lock when it's done. The Java programming language provides two basic synchronization constructs to use those intrinsic locks, synchronized methods and synchronized statements. To make a synchronized method in Java, simply add the keyword synchronized to the method's declaration. When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object. That will prevent other threads that invoke a synchronized method on the same object from interleaving execution. When a thread tries to invoke a synchronized method while another thread is executing a synchronized method for that same object, the second thread will suspend execution until the first thread is done and exits. To demonstrate that in…

Contents