Concurrent ArrayList read/write

I have a situation where one thread puts data in an ArrayList and another thread reads that data. I am not really concerned whether the thread that reads the data can instantly tell that the data is there, but rather if there is a chance the reader thread might not ever see the data at all. Here is an example:
public class Main {


final static ArrayList<Integer> list= new ArrayList<>();

public static void main(String[] args) {
Thread writer = new Thread(Main::write);
Thread reader = new Thread(Main::read);
writer.start();
reader.start();
}
public static void write(){
while (true){
list.add(1);
}
}
public static void read(){
int currentIndex=0;
while (true){
if(currentIndex>=list.size()){
try {
Thread.sleep(1);
continue;
} catch (InterruptedException e) {
return;
}
}
int element = list.get(currentIndex);
currentIndex++;
//do stuff with element...
}
}
}
public class Main {


final static ArrayList<Integer> list= new ArrayList<>();

public static void main(String[] args) {
Thread writer = new Thread(Main::write);
Thread reader = new Thread(Main::read);
writer.start();
reader.start();
}
public static void write(){
while (true){
list.add(1);
}
}
public static void read(){
int currentIndex=0;
while (true){
if(currentIndex>=list.size()){
try {
Thread.sleep(1);
continue;
} catch (InterruptedException e) {
return;
}
}
int element = list.get(currentIndex);
currentIndex++;
//do stuff with element...
}
}
}
In this scenario if for some reason the writer thread is taking a while to add something to the list, is it possible the reader thread might do something like cache the entire list and pretty much never see when a new element is added so it just keeps sleeping? And if it is possible is there a way to prevent it without synchronizing access to the entire structure, because I really don't need to. I have been running my program like this for quite some time and haven't run into any issues, but this potential problem lingers in the back of my mind.
1 Reply
JavaBot
JavaBot10mo ago
This post has been reserved for your question.
Hey @nikcho-kouhai! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here. 💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Want results from more Discord servers?
Add your server