Saturday, April 24, 2010

Terracota HelloWorld

Here you can find step by step How to for creating Terracotta cluster application

1. Download and install Terracotta

2. Create the main test class

import java.util.List;
import java.util.ArrayList;
import java.util.Date;

public class HelloWorld {

private List<Child> children = new ArrayList<Child>();

public void sayHello() {
synchronized (children) {
Child myChild = new Child(new Date());
children.add(myChild);
for (Child child : children) {
System.out.println("Hello "
+ child.getBirthdate());
}
}
}

public static void main(String[] args) {
new HelloWorld().sayHello();
}
}

3. Create the class for storing in Terracotta

import java.util.Date;

//Not Serializable!
class Child {

private Date birthdate;

public Child(Date birthdate) {
this.birthdate = birthdate;
}

public Date getBirthdate() {
return birthdate;
}

}

4. Compile them

5. Create the config file tc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<tc:tc-config xmlns:tc="http://www.terracotta.org/config">
<application>
<dso>
<roots>
<root><field-name>HelloWorld.children</field-name></root>
</roots>
<locks>
<autolock>
<method-expression>* HelloWorld*.*(..)</method-expression>
</autolock>
</locks>
<instrumented-classes>
<include>
<class-expression>Child</class-expression>
</include>
</instrumented-classes>
</dso>
</application>
</tc:tc-config>

6. Start the server:

$ start-tc-server.sh

8. Start a client:

$ dso-java.sh -Dtc.config=tc-config.xml HelloWorld

Output: Hello Thu Dec 13 17:46:58 CET 2007

7. After starting the 2nd client:

Hello Thu Dec 13 17:46:58 CET 2007
Hello Thu Dec 13 17:47:06 CET 2007

As you see, the state is preserved in the server between executions.