JChannel ch=new JChannel("udp.xml");
, I can construct the channel programmatically:
JChannel ch=new JChannel(false); // 1 ProtocolStack stack=new ProtocolStack(); // 2 ch.setProtocolStack(stack); // 3 stack.addProtocol(new UDP().setValue("ip_ttl", 8)); .addProtocol(new PING()) .addProtocol(new MERGE2()) .addProtocol(new FD_SOCK()) .addProtocol(new FD_ALL().setValue("timeout", 12000)); .addProtocol(new VERIFY_SUSPECT()) .addProtocol(new BARRIER()) .addProtocol(new NAKACK()) .addProtocol(new UNICAST2()) .addProtocol(new STABLE()) .addProtocol(new GMS()) .addProtocol(new UFC()) .addProtocol(new MFC()) .addProtocol(new FRAG2()); // 4 stack.init(); // 5
First, a JChannel is created (1). The 'false' argument means that the channel must not create its own protocol stack, because we create it (2) and stick it into the channel (3).
Next, all protocols are created and added to the stack (4). This needs to happen in the order in which we want the protocols to be, so the first protocol added is the transport protocol (UDP in the example).
Note that we can use Protocol.setValue(String attr_name, Object attr_value) to configure each protocol instance. We can also use regular setters if available.
Finally, we call init() (5), which connects the protocol list correctly and calls init() on every instance. This also handles shared transports correctly. For an example of how to create a shared transport with 2 channels on top see ProgrammaticApiTest.
I see mainly 3 use cases where programmatic creation of a channel is preferred over declarative creation:
- Someone hates XML (I'm not one of them) :-)
- Unit tests
- Projects consuming JGroups might have their own configuration mechanism (e.g. GUI, properties file, different XML configuration etc) and don't want to use the XML cofiguration mechanism shipped with JGroups.