Search code examples
javarestarraylistlockingsynchronized

Java rest server: avoid the removal of an item while processing it


I have an arrayList which is static in the class.

In the beginning of each request, I remove all the obsolete items: arrayList.entrySet().removeIf(entry -> entry.getValue().isObsolete()); The removal is done if the item is older than 1 hour. this method is synchronized.

Each API use an item from the list, based on a parameter. If it's in the list, it takes it from there, otherwise it creates a new item and adds it to the list. The API updates the item's data with a certain logic.

How can I avoid the situation where I update a data of an item in API x while API y that has just been called, removes it?

Do I have to synchronized all my APIs? Do I have to lock arrayList object in the beginning of each API? Is there a better/cleaner way to do it?

Thanks


Solution

  • Firstly using a static array list to track objects across service calls is not really a good idea. You might want use something like Terracota or ehCache for maintaining a cache across your service implementations. This will not only free you from worrying about the synchronization issues that you mentioned, but also render scalability , along with performance to your implementation.

    Nevertheless still should you intend to follow a static Map implementation; then use Collections.synchronizedList() to obtain a synchronized representation of your map, and use the same in your methods. Following is a sample usage -

    List<String> cacheList = Collections.synchronizedList(new ArrayList<String>());