- выполнять Bot#run синхронно.
- совместное использование ресурса () между другими ботами и потоками.
Код: Выделить всё
Bot.responseData or.. more
- http-запрос -> получить случайное значение с сервера (например, f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454). (сервер всегда возвращает случайное значение!)
- сохранить значение в Bot.responseData.
- http-запрос (используйте Bot.responseData в качестве параметра) -> верните JSON.
- сохраните JSON в Bot.statistics.
- Cleanup Bot.responseData = null.
Код: Выделить всё
public class Bot
{
private final BotStatistic statisic = new BotStatistic();
private final Object mutex = new Object();
private String responseData;
void run()
{
synchronized(mutex)
{
String myHost = "http://myhost";
firstCall(myHost)
secondCall(myHost);
cleanup();
}
}
private void firstCall(String host)
{
// first http call -> responseData = "f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454";
}
private void secondCall(String host)
{
// second http call(responseData) ->
// JSON {"success": true, "requestValue": "f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454"}
statistic.add(json);
}
private void cleanup()
{
this.responseData=null;
}
}
Код: Выделить всё
public class BotRunner implements Runnable
{
private final Bot bot;
public BotRunner(Bot bot)
{
this.bot = bot;
}
@Override
public void run()
{
bot.run();
}
}
Код: Выделить всё
//init executor
LocalDateTime termination = LocalDateTime.now().plusSeconds(5L);
while (LocalDateTime.now().isBefore(termination))
{
for (Bot bot : bots)
{
executor.execute(new BotRunner(bot));
}
}
//shutdown & close executor
После выполнения я вижу 1–2% дубликатов Bot.responseData от РАЗНОГО бота. Вот такие дела:
Код: Выделить всё
thread-1 : start (Bot@44g35)
thread-1 : f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454
thread-2 : start (Bot@898g)
thread-2 : f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454
thread-1 : end
thread-2 : end
Код: Выделить всё
thread-1 : start (Bot@44g35)
thread-1 : f8c3de3d-1fea-4d7c-a8b0-29f63c4c3454
thread-2 : start (Bot@898g)
thread-2 : 018b2f19-e79e-7d6a-a56d-29feb6211b04
thread-1 : end
thread-2 : end
Подробнее здесь: https://stackoverflow.com/questions/781 ... olexecutor