Skip to content

Instantly share code, notes, and snippets.

@mgandin
Last active December 25, 2015 17:19
Show Gist options
  • Save mgandin/7012689 to your computer and use it in GitHub Desktop.
Save mgandin/7012689 to your computer and use it in GitHub Desktop.
Concurrent FooBarQix
package fr.mga.foobarqix;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ConcurrentFooBarQix implements Callable<String> {
private int toFooBar;
public ConcurrentFooBarQix(int toFooBar){
this.toFooBar = toFooBar;
}
@Override
public String call() throws Exception {
return fooBarQix(toFooBar);
}
public String fooBarQix(int anInteger) {
String result = "";
if(anInteger %3 == 0)
result += "FOO";
if(anInteger %5 == 0)
result += "BAR";
if(anInteger %7 == 0)
result += "QIX";
String integer = String.valueOf(anInteger);
for(int i = 0; i < integer.length();i++) {
if(integer.charAt(i) == '3')
result += "FOO";
if(integer.charAt(i) == '5')
result += "BAR";
if(integer.charAt(i) == '7')
result += "QIX";
}
return result.equals("") ? integer : result;
}
public static void main(String[] args) throws Exception {
List<Callable<String>> callables = new ArrayList<Callable<String>>();
for(int i=1;i <100; i++) {
ConcurrentFooBarQix concurrentFooBarQix = new ConcurrentFooBarQix(i);
callables.add(concurrentFooBarQix);
}
ExecutorService executorService = new ThreadPoolExecutor(
5,10,5000, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
List<Future<String>> futures = executorService.invokeAll(callables);
for (Future<String> future : futures) {
System.out.println(future.get());
}
executorService.shutdown();
}
}
package fr.mga.foobarqix;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ConcurrentFooBarQixTest {
private ConcurrentFooBarQix concurrentFooBarQix;
@Before
public void setUp() {
concurrentFooBarQix = new ConcurrentFooBarQix(0);
}
@Test
public void shoud_return_number() {
Assert.assertEquals("1", concurrentFooBarQix.fooBarQix(1));
}
@Test public void should_return_foo() {
Assert.assertEquals("FOOFOO",concurrentFooBarQix.fooBarQix(3));
Assert.assertEquals("FOO",concurrentFooBarQix.fooBarQix(6));
Assert.assertEquals("FOO",concurrentFooBarQix.fooBarQix((13)));
}
@Test public void should_return_bar() {
Assert.assertEquals("BARBAR",concurrentFooBarQix.fooBarQix(5));
Assert.assertEquals("BAR",concurrentFooBarQix.fooBarQix(10));
Assert.assertEquals("BAR",concurrentFooBarQix.fooBarQix(52));
}
@Test public void should_return_qix() {
Assert.assertEquals("QIXQIX",concurrentFooBarQix.fooBarQix(7));
}
@Test public void should_return_foobarqix() {
Assertions.assertThat(fooBarQix.fooBarQix(35)).isEqualTo("BARQIXFOOBAR");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment