0

Ok, I want to store chat messages into Global variables instead of DB because my system does not use Relational DB. It uses NoSQL Google datastore and write and read data from datastore could be expensive.

Let see this Java List Global Variable

public List myList = new ArrayList();

Now we have 3 functions:

public void insert(){
   myList.add(string);
}

public void remove(){
   myList.remove(string);
}

public void retrieve(){
    String str = myList.get(i);
    // do something
}

Suppose that insert, retrieve and remove run concurrently every X seconds

Timer timer = new Timer();
timer.schedule(new insert(), 0, 5000);
timer.schedule(new remove(), 0, 3000);
timer.schedule(new retrieve(), 0, 4000);

If that is the case, then how does Java List Global Variable Manage Insert, Retrieve & Remove Items when many Insert/retrieve, remove functions are accessing it?

Does it adhere to some certain rules so that we can know how to control it properly?

1
  • 2
    you would get ConcurrentModificationException. Use better concurrent data structure. Commented Jan 7, 2016 at 17:06

1 Answer 1

0

ArrayList is not thread-safe and so you would get a ConcurrentModificationException.

Use Collections.synchronizedList() instead.

Sign up to request clarification or add additional context in comments.

7 Comments

What is the differences? can you give some examples?
Take a look at the documentation: docs.oracle.com/javase/7/docs/api/java/util/…
So, when the insert() function is running then remove() & retrieve() function will be blocked right?
It means that when an operation on the list is being performed no other operation can happen until the first one is finished. So yes, when insert() is in effect, remove() & retrieve() will have to wait.
someone saif that CopyOnWriteArrayList is better stackoverflow.com/questions/11360401/java-synchronized-list
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.