Fix race condition when modifying mainPool
Tzal3x opened this issue · 2 comments
There is a race condition happening when we are modifying the ExecutorServiceHandler.mainPool
.
mainPool
is a shared resource that gets modified by concurrent threads.
Whenever we are calling ExecutorServiceHandler.execute
multiple times -concurrently-, we are implicitly modifying the
mainPool
, with each thread having an incorrect state of it.
e.g.
const mainPool = [1,2,3,4,5] // mainPool is not an Array of Ints in our codebase but assume this for the example
Promise.all([
eshandler.addWorker(...), // Thread A
eshandler.addWorker(...), // Thread B
eshandler.addWorker(...), // Thread C
])
Each thread starts at the same time, meaning that all three of them assume the state of the mainPool
is the same.
Therefore it is possible that the worker's objects created by each thread could overlap with the other threads.
i.e. it's possible for this to happen workerA.objects = [1,2,3]
,workerB.objects=[1,2]
, workerC.objects=[3,4,5]
.
We need to refactor the code to ensure thread safety.
Proposed plan of actions:
- try to generate a testing example that causes the problem (the race condition) 100% of the execution times.
- apply the proposed solution (mutex semaphore)
- check that the test succeeds