8.5.13

Verifying Multi-threading Feature of Spring Integration Message Endpoints

I wanted to verify that Spring Integration would handle message in a concurrent manner. So I built this sample project.

demo-multithreading.xml


<beans ...>
<bean id="taskExec" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="10" />
</bean>

<int:gateway id="gateway" service-interface="sdemo.SimpleGateway"/>

<bean id="service" class="demo.SimpleDelayedHandler"/>

<int:service-activator input-channel="channel-in" ref="service"/>

</beans>

SimpleGateway.java


public interface SimpleGateway {
@Gateway(requestChannel = "channel-in")
public Message<String> sayHello(Message<String> helloMsg);
}

SimpleDelayedHandler.java

public class SimpleDelayedHandler {

@ServiceActivator
public void justDelay(Object obj) throws Exception {
System.out.println("Delays in thread " + Thread.currentThread().getId());
TimeUnit.SECONDS.sleep(new Random().nextInt(20));
System.out.println("Ends Delaying in thread " + Thread.currentThread().getId());
}
}


Test.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:demo-multithreading.xml" } )
public class Test {

@Autowired SimpleGateway gateway;
@Autowired TaskExecutor taskExec;

@Test
public void test() throws Exception {
Runnable r = new Runnable() {

@Override
public void run() {
System.out.println("Saying hello from thread : " + Thread.currentThread().getId());
gateway.sayHello(MessageBuilder.withPayload("").build());
}
};

for(int k=0; k<10; ++k) {
taskExec.execute(r);
}

TimeUnit.MINUTES.sleep(1);
}
}

Output:


Saying hello from thread : 11
Saying hello from thread : 12
Saying hello from thread : 13
Saying hello from thread : 14
Saying hello from thread : 16
Saying hello from thread : 18
Saying hello from thread : 20
Saying hello from thread : 17
Saying hello from thread : 15
Saying hello from thread : 19
Delays in thread 17
Delays in thread 15
Delays in thread 20
Delays in thread 14
Delays in thread 16
Delays in thread 12
Delays in thread 13
Delays in thread 11
Delays in thread 18
Delays in thread 19
Ends Delaying in thread 12
Ends Delaying in thread 11
Ends Delaying in thread 19
Ends Delaying in thread 14
Ends Delaying in thread 16
Ends Delaying in thread 13
Ends Delaying in thread 20
Ends Delaying in thread 18
Ends Delaying in thread 17
Ends Delaying in thread 15




No comments: