How to synchronize threads across multiple JVMs

Sometimes, you want to start the job in multiple JVMs only when all the VM has started. This scenario often comes up with multiplayer games. Let's take a pod racing game for example. The players need to start at the same time and each game server handles 1 player (for simplicity's sake)

Starting from Java 5, there's a CyclicBarrier to synchronize threads and is a perfect tool for this. However, it only handles threads in 1 VM. D'oh! Here's where Terracotta comes in. If you make that CyclicBarrier a shared object, Terracotta will handle the clustering for you, transparently (no API). All of a sudden, your CyclicBarrier object will be seen across all the VMs participated in the game. 

Here's an example of how to do it. First, let's take a look at the PodRacer class

  1. package demo;  
  2.   
  3. import java.util.concurrent.CyclicBarrier;  
  4.   
  5. public class PodRacer {  
  6.   public final static int     COUNT   = 2;  
  7.   private final CyclicBarrier barrier = new CyclicBarrier(COUNT);  
  8.   private String              name;  
  9.   
  10.   public PodRacer(String name) {  
  11.     this.name = name;  
  12.   }  
  13.   
  14.   public void ready() {  
  15.     System.out.println(name + ": ready");  
  16.   }  
  17.   
  18.   public void set() throws Exception {  
  19.     /* in Terracotta world, all threads in different VMs will block here */  
  20.     barrier.await();  
  21.   }  
  22.   
  23.   public void go() throws Exception {  
  24.     System.out.println(name + ": go");  
  25.     Thread.sleep((int) (Math.random() * 5000) + 10);  
  26.     System.out.println(name + ": arrived at " + System.currentTimeMillis());  
  27.   }  
  28.   
  29.   public static void main(String[] args) throws Exception {  
  30.     PodRacer racer = new PodRacer(System.getProperty("racer.name""unknown"));  
  31.     racer.ready();  
  32.     racer.set();  
  33.     racer.go();  
  34.   }  
  35. }  



Notice I hardcoded number of racers here to 2 but it can be made dynamic. If you run this class just like a normal Java program, it will block at racer.set() call because there's only 1 thread arriving at the barrier whereas it requires 2 for the barrier to be lifted. And if you don't use Terracotta underneath, it doesn't matter how many VMs you start, it will just block there.

Next, I'll add Terracotta into the mix and share the barrier object. That can be achieved by marking it in Terracotta configuration file tc-config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <con:tc-config xmlns:con="http://www.terracotta.org/config">  
  3.   <servers>  
  4.     <server host="%i" name="localhost">  
  5.       <dso-port>9510</dso-port>  
  6.       <jmx-port>9520</jmx-port>  
  7.       <data>terracotta/server-data</data>  
  8.       <logs>terracotta/server-logs</logs>  
  9.     </server>  
  10.   </servers>  
  11.   <clients>  
  12.     <logs>terracotta/client-logs</logs>  
  13.   </clients>  
  14.   <application>  
  15.     <dso>  
  16.       <instrumented-classes/>  
  17.       <roots>  
  18.         <root>  
  19.           <field-name>demo.PodRacer.barrier</field-name>  
  20.         </root>  
  21.       </roots>  
  22.     </dso>  
  23.   </application>  
  24. </con:tc-config>  



And that's it. When I start 2 JVMs running PodRacer class with Terracotta, I will efficiently have 2 threads calling racer.set() on the shared barrier

To make it even easier to try out with Terracotta, there's a Maven 2 plugin that will handle starting up your project with Terracotta enabled. Here's the pom.xml of my project:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.   <modelVersion>4.0.0</modelVersion>  
  4.   <groupId>PodRacing</groupId>  
  5.   <artifactId>PodRacing</artifactId>  
  6.   <version>0.0.1</version>  
  7.   <build>  
  8.     <plugins>  
  9.       <plugin>  
  10.         <artifactId>maven-compiler-plugin</artifactId>  
  11.         <configuration>  
  12.           <source>1.5</source>  
  13.           <target>1.5</target>  
  14.         </configuration>  
  15.       </plugin>  
  16.       <plugin>  
  17.         <groupId>org.terracotta.maven.plugins</groupId>  
  18.         <artifactId>tc-maven-plugin</artifactId>  
  19.         <version>1.0.3</version>  
  20.         <executions>  
  21.           <execution>  
  22.             <phase>package</phase>  
  23.             <goals>  
  24.               <goal>bootjar</goal>  
  25.             </goals>  
  26.           </execution>  
  27.         </executions>  
  28.           
  29.         <configuration>  
  30.           <processes>  
  31.             <process nodeName="racer1"   
  32.                      className="demo.PodRacer"  
  33.                      jvmargs="-Dracer.name=Anakin"/>  
  34.             <process nodeName="racer2"   
  35.                      className="demo.PodRacer"  
  36.                      jvmargs="-Dracer.name=Sebulba"/>  
  37.           </processes>  
  38.             
  39.         </configuration>  
  40.       </plugin>  
  41.     </plugins>  
  42.   </build>  
  43.   <pluginRepositories>  
  44.     <pluginRepository>  
  45.       <releases />  
  46.       <snapshots />  
  47.       <id>terracotta</id>  
  48.       <url>http://download.terracotta.org/maven2</url>  
  49.     </pluginRepository>  
  50.   </pluginRepositories>  
  51. </project>  



See how I defined 2 racers through the process element in the plugin configuration. That will start 2 distinct VMs with Terracotta enabled. The output looks something like this:

[INFO] Starting DSO nodes 
[INFO] Starting node racer1: c:\jdk\jdk1.6.0_02\jre/bin/java.exe -Dcom.tc.l1.modules.repositories=file:/C:/Users/hhuynh/.m2/repository/ -Dtc.nodeName=racer1 -Dtc.numberOfNodes=2 -Dtc.config=d:\work\workspace\projects\PodRacing\tc-config.xml -Dtc.classpath=file:/c:/Users/hhuynh/AppData/Local/Temp/tc-classpath37736.tmp -Dtc.session.classpath=/C:/Users/hhuynh/.m2/repository/org/terracotta/tc-session/2.5.0/tc-session-2.5.0.jar -Dcom.tc.l1.modules.repositories=file:/C:/Users/hhuynh/.m2/repository/ -Xbootclasspath/p:d:\work\workspace\projects\PodRacing\target\dso-boot.jar -Dracer.name=Anakin -cp d:\work\workspace\projects\PodRacing\target\classes; demo.PodRacer
[INFO] Starting node racer2: c:\jdk\jdk1.6.0_02\jre/bin/java.exe -Dcom.tc.l1.modules.repositories=file:/C:/Users/hhuynh/.m2/repository/ -Dtc.nodeName=racer2 -Dtc.numberOfNodes=2 -Dtc.config=d:\work\workspace\projects\PodRacing\tc-config.xml -Dtc.classpath=file:/c:/Users/hhuynh/AppData/Local/Temp/tc-classpath37737.tmp -Dtc.session.classpath=/C:/Users/hhuynh/.m2/repository/org/terracotta/tc-session/2.5.0/tc-session-2.5.0.jar -Dcom.tc.l1.modules.repositories=file:/C:/Users/hhuynh/.m2/repository/ -Xbootclasspath/p:d:\work\workspace\projects\PodRacing\target\dso-boot.jar -Dracer.name=Sebulba -cp d:\work\workspace\projects\PodRacing\target\classes; demo.PodRacer
[INFO] ------------------------------------------------------------------------

[INFO] [racer2] Sebulba: ready
[INFO] [racer1] Anakin: ready
[INFO] [racer1] Anakin: go
[INFO] [racer2] Sebulba: go
[INFO] [racer2] Sebulba: arrived at 1202406914274
[INFO] Finished node racer2
[INFO] [racer1] Anakin: arrived at 1202406915125
[INFO] Finished node racer1



Ouch, Anakin sucked!

Download the Maven project and try it out. Have fun.


你可能感兴趣的:(java,jvm)