Skip to content
This repository has been archived by the owner on Aug 13, 2023. It is now read-only.

AppExecutors Class "Race condition" #14

Open
ghost opened this issue Mar 22, 2018 · 0 comments
Open

AppExecutors Class "Race condition" #14

ghost opened this issue Mar 22, 2018 · 0 comments

Comments

@ghost
Copy link

ghost commented Mar 22, 2018

My issue addresses the part in the class named "AppExecutors", at line 47 there is a method named "getInstance", at the section :
public static AppExecutors getInstance() { if (sInstance == null) { synchronized (LOCK) { sInstance = new AppExecutors(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(3), new MainThreadExecutor()); } } return sInstance; }

This synchronized block does not actually avoid the race condition; consider the following scenario :
Thread 1 & Thread 2, they both call "getInstance" method at the same exact time for the very first time, then both will evaluate "if (sInstance == null)" to be True, thus the first one to acquire the lock will instantiate "sInstance" and then the other thread will acquire the lock afterwards thus, re-instantiating the "sInstance" variable once again, which is what we were trying to avoid in the first place.

So, to only instantiate "sInstance" only exactly once no matter what, you could either swap the condition line with the synchronized line like so :
synchronized (LOCK) { if (sInstance == null) { sInstance = new AppExecutors(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(3), new MainThreadExecutor()); } }

Or to actually remove the synchronized block altogether and just make the whole function Synchronized like so :
synchronized public static AppExecutors getInstance() { if (sInstance == null) { sInstance = new AppExecutors(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(3), new MainThreadExecutor()); } return sInstance; }

This will ensure 100% that "sInstance" will only be instantiated exactly once.

Thanks for your support.

@ghost ghost changed the title AppExecutors Class possible "Race condition" AppExecutors Class "Race condition" Mar 22, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

0 participants