We will create a new starter class called Main that can spawn either a Producer or a Consumer thread depending on the command line argument:
The Main class:
public class Main {
Jobs jobs = new Jobs();
public Main(boolean isProducer){
if(isProducer) new Producer(jobs).start();
else new Consumer(jobs).start();
}
public static void main(String[] args){
new Main(args.length>0 &&
"producer".equals(args.length[0]));
}
}
All we want to do now is to tell Terracotta to share jobs field of this Main class and make sure that all the Producers and Consumers use the methods of Jobs class in a mutually exclusive manner. The config file to do this is really simple -
<?xml version="1.0" encoding="UTF-8"?>
<tc:tc-config xmlns:tc="http://www.terracotta.org/config">
<application>
<dso>
<roots>
<root>
<field-name>Main.jobs</field-name>
</root>
</roots>
<locks>
<autolock>
<method-expression>* Jobs*.*(..)</method-expression>
<lock-level>write</lock-level>
</autolock>
</locks>
<instrumented-classes>
<include><class-expression>.*</class-expression></include>
</instrumented-classes>
</dso>
</application>
</tc:tc-config>
That's all we need to do in terms of coding!!!
Running the application:
To run the application,
1. First we need to run the Terracotta Server using start-tc-server.bat available in the bin directory of Terracotta installation.
2. Launch our Main class using dso-java.bat script (available in bin) instead of directly using java. We pass the config file name as a system property and our class name :
c:\works\test\>dso-java -Dtc.config tc-config-pc.xml Main consumer
I started up the consumer first and I can see that it gets stuck on the wait() because there is no Job in Jobs.
3. Start the producer in another cmd window:
c:\works\test\>dso-java -Dtc.config tc-config-pc.xml Main producer
That's it!!! As soon as producer starts putting Job instances in jobs, the consumer starts getting them. No RMI, No EJB, No CORBA and we have shared an object with multiple JVMs. No code changes required in the main fiunctionality to make it work on multiple JVMs.
To understand how it works under the hood, please do read the documentation at Terracotta website.
1 comment:
Hi,
Looking forward to your GridGain analysis :)
I think GridGain benefits will shine not only when you have to execute something on remote node, but also when you need to split a bigger task into smaller subtasks.
Also GridGain's peer-class-loading will come very convenient during development - there is no deployment or extra configuration of remote nodes.
Best,
Dmitriy Setrakyan
GridGain - Grid Computing Made Simple
Post a Comment