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?

Tum
  • 3,614
  • 5
  • 38
  • 63
  • 2
    you would get ConcurrentModificationException. Use better concurrent data structure. – SMA Jan 07 '16 at 17:06

1 Answers1

0

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

Use Collections.synchronizedList() instead.

Arqan
  • 376
  • 1
  • 3
  • 14
  • What is the differences? can you give some examples? – Tum Jan 07 '16 at 17:09
  • Take a look at the documentation: http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList(java.util.List) – Arqan Jan 07 '16 at 17:11
  • So, when the **insert()** function is running then **remove()** & **retrieve()** function will be blocked right? – Tum Jan 07 '16 at 17:14
  • 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. – Arqan Jan 07 '16 at 17:19
  • someone saif that CopyOnWriteArrayList is better http://stackoverflow.com/questions/11360401/java-synchronized-list – Tum Jan 08 '16 at 07:40
  • "Better" is a bold statement. If you want to perform insert or delete operations `Collections.synchronizedList()` will do its job perfectly fine. – Arqan Jan 08 '16 at 09:47
  • I still has **java.util.ConcurrentModificationException** when irritate **Collections.synchronizedList** see this http://stackoverflow.com/questions/6596673/java-concurrentmodificationexception-while-iterating-over-list – Tum Jan 11 '16 at 08:37