I`m trying to make an api-checking app that must send requests asynchronously using the pool of bots while termination date is not reached.
On startup creates a final List<Bot>
is created and will be executed until the termination date. The idea is that at each iteration of the while
cycle, we would iterate through the List<Bot>
and try to launch them through the executor in wrapper BotRunner
. (if the bot is already launched by another thread, we will simply hang on the mutex
monitor and wait for completion Bot#run
from another thread. After that - execute Bot#run
normally).
After execution i see 1-2% of duplicating requests from different bots (server sends correct data i swear). Looks like simple race-condition, but i don't realize what is causes. Is it Bot
? - i suppose not (use synchronized). Is it final List<Bot>
? - is guess no (we don't change state of list)
Bot entity:
public class Bot
{
private final BotStatistic statisic = new BotStatistic();
private final Object mutex = new Object();
private String responseData;
void run()
{
synchronized(mutex) {
// first http call -> responseData = "j43iFS135SFSF";
// second http call(responseData) -> {"success": "true"}
// save to statistic
// responseData = null;
}
}
}
BotRunner entity:
public class BotRunner implements Runnable
{
private final Bot bot;
public BotRunner(Bot bot)
{
this.bot = bot;
}
@Override
public void run()
{
bot.run();
}
}
Trying to execute in this way:
//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
WHAT NOT WORKS:
String -> final StringBuffer
not helps.- Use local method variable
String
not helps.
Could someone say what i did wrong?
mutex.wait()
insynchronized
block???Bot
already implementsRunnable
.Bot
? Is it even important to the Question here? Write your issue description as simply as possible.synchronized
block), the next thread can start the next operation (enter thesynchronized
block). There is no in-between where you could check the result without races. Nor any other place where checking the result could work.BotStatistic
object but for some reason, all your attempts were changes to the unrelatedresponseData
variable?