[concurrency-interest] Converting the AtomicXXXArray inner elements to an array

olivier.dupuy@hrdc-drhc.gc.ca olivier.dupuy@hrdc-drhc.gc.ca
Mon, 26 Jan 2004 15:49:06 -0500


Hello,

I was reviewing this week end the J.U.C. API for the good use I could do of it in a an existing commercial program.

It happens that this C/S program is multi threaded. Each thread collects statistics but the stats are kept together and as a consequence are protected against concurrent access using synchronization. I increment many counters based on the use of the API functions called by the clients and based on their parameters. Most of the threads update the statistics but on a regular basis they are extracted. AtomicInterger/LongArray would be a great fit for this job instead of the existing code.

This is my use case.

We have recently added contructors to the AtomicXXXArray classes for both convenience and speed. At this time, if you want to take a snapshot (>> understand a copy<<) of the AtomicXXXArray inner values for any purpose, you have no other choice than to get every element individually. This is OK but is it efficient (or elegant) ? Specially if you do it often, accessing to the array 'elements' through a method is more CPU intensive than doing a regular array access.

As in many other J.U.C. classes, a 'toArray' method returning an array of int/long would do the trick and would be quick to write even if I understand that in 1.5, custom code doing the copy can be more compact than before. I also understand that this conversion to an array is not "atomic".  However I tend to prefer JDK APIs to be complete when possible and having a method returning an array/Collection of its internal elements is quite standard through the JDK.

I don't see an immediate use for the same toArray method in the AtomicReferenceArray but someone can have one so I would suggest to add it too.

Olivier