I found some examples of Java programs that become deadlocked due to their incorrect use of the “synchronized” keyword. I decided to try to get them to work using the @Synchronized annotation provided by Project Lombok.
First, here is the example from the Really Big Tutorial.
package really.big.tutorial; // from Really Big Tutorial: // http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html /** * * @author ericm */ public class Deadlock { static class Friend { private final String name; public Friend( String name ) { this.name = name; } public String getName() { return this.name; } public synchronized void bow( Friend bower ) { System.out.format("%s: %s has bowed to me!%n", this.name, bower.getName() ); bower.bowBack( this ); } public synchronized void bowBack( Friend bower ) { System.out.format("%s: %s has bowed back to me!%n", this.name, bower.getName() ); } } // end class Friend public static void main( String[] args ) { final Friend alphonse = new Friend( "Alphonse" ); final Friend gaston = new Friend( "Gaston" ); new Thread( new Runnable() { public void run() { alphonse.bow( gaston ); } }).start(); new Thread( new Runnable() { public void run() { gaston.bow( alphonse ); } }).start(); System.out.println( "At the end of main" ); } // end method main } // end class Deadlock
Here is the same program with Lombok:
package really.big.tutorial; // Lombok-ed refactoring of deadlock example from Really Big Tutorial: // http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html import java.util.UUID; import lombok.Synchronized; public class DeadlockLombok { static class Friend { private final Object readLock = new Object[ 0 ]; private final Object readLock2 = new Object[ 0 ]; private final String name; public Friend( String name ) { this.name = name; } public String getName() { return this.name; } @Synchronized( "readLock" ) public void bow( Friend bower ) { System.out.format( "%s: %s has bowed to me!%n", this.name, bower.getName() ); bower.bowBack( this ); } // either one works // @Synchronized( "readLock2" ) public void bowBack( Friend bower ) { @Synchronized public void bowBack( Friend bower ) { System.out.format("%s: %s has bowed back to me!%n", this.name, bower.getName() ); } } // end class Friend public static void main( String[] args ) { final Friend alphonse = new Friend( "Alphonse" ); final Friend gaston = new Friend( "Gaston" ); new Thread(new Runnable() { public void run() { alphonse.bow( gaston ); } }).start(); new Thread(new Runnable() { public void run() { gaston.bow( alphonse ); } }).start(); System.out.println( "At the end of main" ); } // end method main } // end class DeadlockLombok
I will have a few more examples over the next few days.
Image from the Wikipedia page for Jakarta, a province in Indonesia. With Java, the name is usually based on coffee or Indonesia. Image assumed allowed under Fair Use.