java array thread-safety












22















Are there any concurrency problems with one thread reading from one index of an array, while another thread writes to another index of the array, as long as the indices are different?



e.g. (this example not necessarily recommended for real use, only to illustrate my point)



 class Test1
{
static final private int N = 4096;
final private int x = new int[N];
final private AtomicInteger nwritten = new AtomicInteger(0);
// invariant:
// all values x[i] where 0 <= i < nwritten.get() are immutable

// read() is not synchronized since we want it to be fast
int read(int index) {
if (index >= nwritten.get())
throw new IllegalArgumentException();
return x[index];
}
// write() is synchronized to handle multiple writers
// (using compare-and-set techniques to avoid blocking algorithms
// is nontrivial)
synchronized void write(int x_i) {
int index = nwriting.get();
if (index >= N)
throw SomeExceptionThatIndicatesArrayIsFull();
x[index] = x_i;
// from this point forward, x[index] is fixed in stone
nwriting.set(index+1);
}
}


edit: critiquing this example is not my question, I literally just want to know if array access to one index, concurrently to access of another index, poses concurrency problems, couldn't think of a simple example.










share|improve this question





























    22















    Are there any concurrency problems with one thread reading from one index of an array, while another thread writes to another index of the array, as long as the indices are different?



    e.g. (this example not necessarily recommended for real use, only to illustrate my point)



     class Test1
    {
    static final private int N = 4096;
    final private int x = new int[N];
    final private AtomicInteger nwritten = new AtomicInteger(0);
    // invariant:
    // all values x[i] where 0 <= i < nwritten.get() are immutable

    // read() is not synchronized since we want it to be fast
    int read(int index) {
    if (index >= nwritten.get())
    throw new IllegalArgumentException();
    return x[index];
    }
    // write() is synchronized to handle multiple writers
    // (using compare-and-set techniques to avoid blocking algorithms
    // is nontrivial)
    synchronized void write(int x_i) {
    int index = nwriting.get();
    if (index >= N)
    throw SomeExceptionThatIndicatesArrayIsFull();
    x[index] = x_i;
    // from this point forward, x[index] is fixed in stone
    nwriting.set(index+1);
    }
    }


    edit: critiquing this example is not my question, I literally just want to know if array access to one index, concurrently to access of another index, poses concurrency problems, couldn't think of a simple example.










    share|improve this question



























      22












      22








      22


      5






      Are there any concurrency problems with one thread reading from one index of an array, while another thread writes to another index of the array, as long as the indices are different?



      e.g. (this example not necessarily recommended for real use, only to illustrate my point)



       class Test1
      {
      static final private int N = 4096;
      final private int x = new int[N];
      final private AtomicInteger nwritten = new AtomicInteger(0);
      // invariant:
      // all values x[i] where 0 <= i < nwritten.get() are immutable

      // read() is not synchronized since we want it to be fast
      int read(int index) {
      if (index >= nwritten.get())
      throw new IllegalArgumentException();
      return x[index];
      }
      // write() is synchronized to handle multiple writers
      // (using compare-and-set techniques to avoid blocking algorithms
      // is nontrivial)
      synchronized void write(int x_i) {
      int index = nwriting.get();
      if (index >= N)
      throw SomeExceptionThatIndicatesArrayIsFull();
      x[index] = x_i;
      // from this point forward, x[index] is fixed in stone
      nwriting.set(index+1);
      }
      }


      edit: critiquing this example is not my question, I literally just want to know if array access to one index, concurrently to access of another index, poses concurrency problems, couldn't think of a simple example.










      share|improve this question
















      Are there any concurrency problems with one thread reading from one index of an array, while another thread writes to another index of the array, as long as the indices are different?



      e.g. (this example not necessarily recommended for real use, only to illustrate my point)



       class Test1
      {
      static final private int N = 4096;
      final private int x = new int[N];
      final private AtomicInteger nwritten = new AtomicInteger(0);
      // invariant:
      // all values x[i] where 0 <= i < nwritten.get() are immutable

      // read() is not synchronized since we want it to be fast
      int read(int index) {
      if (index >= nwritten.get())
      throw new IllegalArgumentException();
      return x[index];
      }
      // write() is synchronized to handle multiple writers
      // (using compare-and-set techniques to avoid blocking algorithms
      // is nontrivial)
      synchronized void write(int x_i) {
      int index = nwriting.get();
      if (index >= N)
      throw SomeExceptionThatIndicatesArrayIsFull();
      x[index] = x_i;
      // from this point forward, x[index] is fixed in stone
      nwriting.set(index+1);
      }
      }


      edit: critiquing this example is not my question, I literally just want to know if array access to one index, concurrently to access of another index, poses concurrency problems, couldn't think of a simple example.







      java arrays concurrency






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 15 '09 at 17:17







      Jason S

















      asked Jul 15 '09 at 16:33









      Jason SJason S

      107k135488820




      107k135488820
























          5 Answers
          5






          active

          oldest

          votes


















          13














          While you will not get an invalid state by changing arrays as you mention, you will have the same problem that happens when two threads are viewing a non volatile integer without synchronization (see the section in the Java Tutorial on Memory Consistency Errors). Basically, the problem is that Thread 1 may write a value in space i, but there is no guarantee when (or if) Thread 2 will see the change.



          The class java.util.concurrent.atomic.AtomicIntegerArray does what you want to do.






          share|improve this answer


























          • thanks... drat, I wanted to use a byte array and it looks like there's no such Atomic animal.... I guess I'll just use synchronized methods and keep it simple.

            – Jason S
            Jul 15 '09 at 17:24






          • 2





            If you have a lot more reads than writes you might want to look at java.util.concurrent.locks.ReadWriteLock

            – Kathy Van Stone
            Jul 15 '09 at 17:32











          • huh, interesting...

            – Jason S
            Jul 15 '09 at 17:34











          • just to make sure I understand: so if the CPU execution order is (1) thread A writes 33 to x[0], (2) thread A sets a "safe flag" saying it's safe to read x[0], (3) thread B reads the "safe flag" saying it's safe to read x[0], (4) thread B reads x[0], there's no guarantee the memory propagation will happen even if I use synchronization on the "safe flag"; I have to use synchronization in a way that includes the read/write of x[0] in the synchronization process?

            – Jason S
            Jul 15 '09 at 17:41











          • According to the Memory Consitency Properties (java.sun.com/javase/6/docs/api/java/util/concurrent/…) documentation, if the safe flag is always false until 2, then (1) "happens-before" (2) and (3) "happens-before" (4) because they are in a single thread, and (2) "happens-before" (3) because of synchronization. However, if you are going to use a lock and a boolean for each byte you are better off with an AtomicIntegerArray as you will using about as much space (with less complexity)

            – Kathy Van Stone
            Jul 15 '09 at 18:11



















          4














          The example has a lot of stuff that differs from the prose question.



          The answer to that question is that distinct elements of an array are accessed independently, so you don't need synchronization if two threads change different elements.



          However, the Java memory model makes no guarantees (that I'm aware of) that a value written by one thread will be visible to another thread, unless you synchronize access.



          Depending on what you're really trying to accomplish, it's likely that java.util.concurrent already has a class that will do it for you. And if it doesn't, I still recommend taking a look at the source code for ConcurrentHashMap, since your code appears to be doing the same thing that it does to manage the hash table.






          share|improve this answer































            1














            I am not really sure if synchronizing only the write method, while leaving the read method unsychronized would work. Not really what are all the consequences, but at least it might lead to read method returning some values that has just been overriden by write.






            share|improve this answer































              1














              Yes, as bad cache interleaving can still happen in a multi-cpu/core environment. There are several options to avoid it:




              • Use the Unsafe Sun-private library to atomically set an element in an array (or the jsr166y added feature in Java7

              • Use AtomicXYZ array

              • Use custom object with one volatile field and have an array of that object.

              • Use the ParallelArray of jsr166y addendum instead in your algorithm






              share|improve this answer































                1














                Since read() is not synchronized you could have the following scenario:



                Thread A enters write() method
                Thread A writes to nwriting = 0;
                Thread B reads from nwriting =0;
                Thread A increments nwriting. nwriting=1
                Thread A exits write();


                Since you want to guarantee that your variable addresses never conflict, what about something like (discounting array index issues):



                int i;
                synchronized int curr(){ return i; }
                synchronized int next(){ return ++i;}

                int read( ) {
                return values[curr()];
                }

                void write(int x){
                values[next()]=x;
                }





                share|improve this answer


























                • thanks, but not my question & your scenario can't happen (steps 2 and 3 would never occur)

                  – Jason S
                  Jul 15 '09 at 17:20











                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1132507%2fjava-array-thread-safety%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                13














                While you will not get an invalid state by changing arrays as you mention, you will have the same problem that happens when two threads are viewing a non volatile integer without synchronization (see the section in the Java Tutorial on Memory Consistency Errors). Basically, the problem is that Thread 1 may write a value in space i, but there is no guarantee when (or if) Thread 2 will see the change.



                The class java.util.concurrent.atomic.AtomicIntegerArray does what you want to do.






                share|improve this answer


























                • thanks... drat, I wanted to use a byte array and it looks like there's no such Atomic animal.... I guess I'll just use synchronized methods and keep it simple.

                  – Jason S
                  Jul 15 '09 at 17:24






                • 2





                  If you have a lot more reads than writes you might want to look at java.util.concurrent.locks.ReadWriteLock

                  – Kathy Van Stone
                  Jul 15 '09 at 17:32











                • huh, interesting...

                  – Jason S
                  Jul 15 '09 at 17:34











                • just to make sure I understand: so if the CPU execution order is (1) thread A writes 33 to x[0], (2) thread A sets a "safe flag" saying it's safe to read x[0], (3) thread B reads the "safe flag" saying it's safe to read x[0], (4) thread B reads x[0], there's no guarantee the memory propagation will happen even if I use synchronization on the "safe flag"; I have to use synchronization in a way that includes the read/write of x[0] in the synchronization process?

                  – Jason S
                  Jul 15 '09 at 17:41











                • According to the Memory Consitency Properties (java.sun.com/javase/6/docs/api/java/util/concurrent/…) documentation, if the safe flag is always false until 2, then (1) "happens-before" (2) and (3) "happens-before" (4) because they are in a single thread, and (2) "happens-before" (3) because of synchronization. However, if you are going to use a lock and a boolean for each byte you are better off with an AtomicIntegerArray as you will using about as much space (with less complexity)

                  – Kathy Van Stone
                  Jul 15 '09 at 18:11
















                13














                While you will not get an invalid state by changing arrays as you mention, you will have the same problem that happens when two threads are viewing a non volatile integer without synchronization (see the section in the Java Tutorial on Memory Consistency Errors). Basically, the problem is that Thread 1 may write a value in space i, but there is no guarantee when (or if) Thread 2 will see the change.



                The class java.util.concurrent.atomic.AtomicIntegerArray does what you want to do.






                share|improve this answer


























                • thanks... drat, I wanted to use a byte array and it looks like there's no such Atomic animal.... I guess I'll just use synchronized methods and keep it simple.

                  – Jason S
                  Jul 15 '09 at 17:24






                • 2





                  If you have a lot more reads than writes you might want to look at java.util.concurrent.locks.ReadWriteLock

                  – Kathy Van Stone
                  Jul 15 '09 at 17:32











                • huh, interesting...

                  – Jason S
                  Jul 15 '09 at 17:34











                • just to make sure I understand: so if the CPU execution order is (1) thread A writes 33 to x[0], (2) thread A sets a "safe flag" saying it's safe to read x[0], (3) thread B reads the "safe flag" saying it's safe to read x[0], (4) thread B reads x[0], there's no guarantee the memory propagation will happen even if I use synchronization on the "safe flag"; I have to use synchronization in a way that includes the read/write of x[0] in the synchronization process?

                  – Jason S
                  Jul 15 '09 at 17:41











                • According to the Memory Consitency Properties (java.sun.com/javase/6/docs/api/java/util/concurrent/…) documentation, if the safe flag is always false until 2, then (1) "happens-before" (2) and (3) "happens-before" (4) because they are in a single thread, and (2) "happens-before" (3) because of synchronization. However, if you are going to use a lock and a boolean for each byte you are better off with an AtomicIntegerArray as you will using about as much space (with less complexity)

                  – Kathy Van Stone
                  Jul 15 '09 at 18:11














                13












                13








                13







                While you will not get an invalid state by changing arrays as you mention, you will have the same problem that happens when two threads are viewing a non volatile integer without synchronization (see the section in the Java Tutorial on Memory Consistency Errors). Basically, the problem is that Thread 1 may write a value in space i, but there is no guarantee when (or if) Thread 2 will see the change.



                The class java.util.concurrent.atomic.AtomicIntegerArray does what you want to do.






                share|improve this answer















                While you will not get an invalid state by changing arrays as you mention, you will have the same problem that happens when two threads are viewing a non volatile integer without synchronization (see the section in the Java Tutorial on Memory Consistency Errors). Basically, the problem is that Thread 1 may write a value in space i, but there is no guarantee when (or if) Thread 2 will see the change.



                The class java.util.concurrent.atomic.AtomicIntegerArray does what you want to do.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 22 at 21:36









                Sean Bright

                92.4k14113128




                92.4k14113128










                answered Jul 15 '09 at 16:55









                Kathy Van StoneKathy Van Stone

                19.6k22639




                19.6k22639













                • thanks... drat, I wanted to use a byte array and it looks like there's no such Atomic animal.... I guess I'll just use synchronized methods and keep it simple.

                  – Jason S
                  Jul 15 '09 at 17:24






                • 2





                  If you have a lot more reads than writes you might want to look at java.util.concurrent.locks.ReadWriteLock

                  – Kathy Van Stone
                  Jul 15 '09 at 17:32











                • huh, interesting...

                  – Jason S
                  Jul 15 '09 at 17:34











                • just to make sure I understand: so if the CPU execution order is (1) thread A writes 33 to x[0], (2) thread A sets a "safe flag" saying it's safe to read x[0], (3) thread B reads the "safe flag" saying it's safe to read x[0], (4) thread B reads x[0], there's no guarantee the memory propagation will happen even if I use synchronization on the "safe flag"; I have to use synchronization in a way that includes the read/write of x[0] in the synchronization process?

                  – Jason S
                  Jul 15 '09 at 17:41











                • According to the Memory Consitency Properties (java.sun.com/javase/6/docs/api/java/util/concurrent/…) documentation, if the safe flag is always false until 2, then (1) "happens-before" (2) and (3) "happens-before" (4) because they are in a single thread, and (2) "happens-before" (3) because of synchronization. However, if you are going to use a lock and a boolean for each byte you are better off with an AtomicIntegerArray as you will using about as much space (with less complexity)

                  – Kathy Van Stone
                  Jul 15 '09 at 18:11



















                • thanks... drat, I wanted to use a byte array and it looks like there's no such Atomic animal.... I guess I'll just use synchronized methods and keep it simple.

                  – Jason S
                  Jul 15 '09 at 17:24






                • 2





                  If you have a lot more reads than writes you might want to look at java.util.concurrent.locks.ReadWriteLock

                  – Kathy Van Stone
                  Jul 15 '09 at 17:32











                • huh, interesting...

                  – Jason S
                  Jul 15 '09 at 17:34











                • just to make sure I understand: so if the CPU execution order is (1) thread A writes 33 to x[0], (2) thread A sets a "safe flag" saying it's safe to read x[0], (3) thread B reads the "safe flag" saying it's safe to read x[0], (4) thread B reads x[0], there's no guarantee the memory propagation will happen even if I use synchronization on the "safe flag"; I have to use synchronization in a way that includes the read/write of x[0] in the synchronization process?

                  – Jason S
                  Jul 15 '09 at 17:41











                • According to the Memory Consitency Properties (java.sun.com/javase/6/docs/api/java/util/concurrent/…) documentation, if the safe flag is always false until 2, then (1) "happens-before" (2) and (3) "happens-before" (4) because they are in a single thread, and (2) "happens-before" (3) because of synchronization. However, if you are going to use a lock and a boolean for each byte you are better off with an AtomicIntegerArray as you will using about as much space (with less complexity)

                  – Kathy Van Stone
                  Jul 15 '09 at 18:11

















                thanks... drat, I wanted to use a byte array and it looks like there's no such Atomic animal.... I guess I'll just use synchronized methods and keep it simple.

                – Jason S
                Jul 15 '09 at 17:24





                thanks... drat, I wanted to use a byte array and it looks like there's no such Atomic animal.... I guess I'll just use synchronized methods and keep it simple.

                – Jason S
                Jul 15 '09 at 17:24




                2




                2





                If you have a lot more reads than writes you might want to look at java.util.concurrent.locks.ReadWriteLock

                – Kathy Van Stone
                Jul 15 '09 at 17:32





                If you have a lot more reads than writes you might want to look at java.util.concurrent.locks.ReadWriteLock

                – Kathy Van Stone
                Jul 15 '09 at 17:32













                huh, interesting...

                – Jason S
                Jul 15 '09 at 17:34





                huh, interesting...

                – Jason S
                Jul 15 '09 at 17:34













                just to make sure I understand: so if the CPU execution order is (1) thread A writes 33 to x[0], (2) thread A sets a "safe flag" saying it's safe to read x[0], (3) thread B reads the "safe flag" saying it's safe to read x[0], (4) thread B reads x[0], there's no guarantee the memory propagation will happen even if I use synchronization on the "safe flag"; I have to use synchronization in a way that includes the read/write of x[0] in the synchronization process?

                – Jason S
                Jul 15 '09 at 17:41





                just to make sure I understand: so if the CPU execution order is (1) thread A writes 33 to x[0], (2) thread A sets a "safe flag" saying it's safe to read x[0], (3) thread B reads the "safe flag" saying it's safe to read x[0], (4) thread B reads x[0], there's no guarantee the memory propagation will happen even if I use synchronization on the "safe flag"; I have to use synchronization in a way that includes the read/write of x[0] in the synchronization process?

                – Jason S
                Jul 15 '09 at 17:41













                According to the Memory Consitency Properties (java.sun.com/javase/6/docs/api/java/util/concurrent/…) documentation, if the safe flag is always false until 2, then (1) "happens-before" (2) and (3) "happens-before" (4) because they are in a single thread, and (2) "happens-before" (3) because of synchronization. However, if you are going to use a lock and a boolean for each byte you are better off with an AtomicIntegerArray as you will using about as much space (with less complexity)

                – Kathy Van Stone
                Jul 15 '09 at 18:11





                According to the Memory Consitency Properties (java.sun.com/javase/6/docs/api/java/util/concurrent/…) documentation, if the safe flag is always false until 2, then (1) "happens-before" (2) and (3) "happens-before" (4) because they are in a single thread, and (2) "happens-before" (3) because of synchronization. However, if you are going to use a lock and a boolean for each byte you are better off with an AtomicIntegerArray as you will using about as much space (with less complexity)

                – Kathy Van Stone
                Jul 15 '09 at 18:11













                4














                The example has a lot of stuff that differs from the prose question.



                The answer to that question is that distinct elements of an array are accessed independently, so you don't need synchronization if two threads change different elements.



                However, the Java memory model makes no guarantees (that I'm aware of) that a value written by one thread will be visible to another thread, unless you synchronize access.



                Depending on what you're really trying to accomplish, it's likely that java.util.concurrent already has a class that will do it for you. And if it doesn't, I still recommend taking a look at the source code for ConcurrentHashMap, since your code appears to be doing the same thing that it does to manage the hash table.






                share|improve this answer




























                  4














                  The example has a lot of stuff that differs from the prose question.



                  The answer to that question is that distinct elements of an array are accessed independently, so you don't need synchronization if two threads change different elements.



                  However, the Java memory model makes no guarantees (that I'm aware of) that a value written by one thread will be visible to another thread, unless you synchronize access.



                  Depending on what you're really trying to accomplish, it's likely that java.util.concurrent already has a class that will do it for you. And if it doesn't, I still recommend taking a look at the source code for ConcurrentHashMap, since your code appears to be doing the same thing that it does to manage the hash table.






                  share|improve this answer


























                    4












                    4








                    4







                    The example has a lot of stuff that differs from the prose question.



                    The answer to that question is that distinct elements of an array are accessed independently, so you don't need synchronization if two threads change different elements.



                    However, the Java memory model makes no guarantees (that I'm aware of) that a value written by one thread will be visible to another thread, unless you synchronize access.



                    Depending on what you're really trying to accomplish, it's likely that java.util.concurrent already has a class that will do it for you. And if it doesn't, I still recommend taking a look at the source code for ConcurrentHashMap, since your code appears to be doing the same thing that it does to manage the hash table.






                    share|improve this answer













                    The example has a lot of stuff that differs from the prose question.



                    The answer to that question is that distinct elements of an array are accessed independently, so you don't need synchronization if two threads change different elements.



                    However, the Java memory model makes no guarantees (that I'm aware of) that a value written by one thread will be visible to another thread, unless you synchronize access.



                    Depending on what you're really trying to accomplish, it's likely that java.util.concurrent already has a class that will do it for you. And if it doesn't, I still recommend taking a look at the source code for ConcurrentHashMap, since your code appears to be doing the same thing that it does to manage the hash table.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jul 15 '09 at 16:42









                    kdgregorykdgregory

                    35.4k106493




                    35.4k106493























                        1














                        I am not really sure if synchronizing only the write method, while leaving the read method unsychronized would work. Not really what are all the consequences, but at least it might lead to read method returning some values that has just been overriden by write.






                        share|improve this answer




























                          1














                          I am not really sure if synchronizing only the write method, while leaving the read method unsychronized would work. Not really what are all the consequences, but at least it might lead to read method returning some values that has just been overriden by write.






                          share|improve this answer


























                            1












                            1








                            1







                            I am not really sure if synchronizing only the write method, while leaving the read method unsychronized would work. Not really what are all the consequences, but at least it might lead to read method returning some values that has just been overriden by write.






                            share|improve this answer













                            I am not really sure if synchronizing only the write method, while leaving the read method unsychronized would work. Not really what are all the consequences, but at least it might lead to read method returning some values that has just been overriden by write.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jul 15 '09 at 16:42









                            Grzegorz OledzkiGrzegorz Oledzki

                            16.4k115386




                            16.4k115386























                                1














                                Yes, as bad cache interleaving can still happen in a multi-cpu/core environment. There are several options to avoid it:




                                • Use the Unsafe Sun-private library to atomically set an element in an array (or the jsr166y added feature in Java7

                                • Use AtomicXYZ array

                                • Use custom object with one volatile field and have an array of that object.

                                • Use the ParallelArray of jsr166y addendum instead in your algorithm






                                share|improve this answer




























                                  1














                                  Yes, as bad cache interleaving can still happen in a multi-cpu/core environment. There are several options to avoid it:




                                  • Use the Unsafe Sun-private library to atomically set an element in an array (or the jsr166y added feature in Java7

                                  • Use AtomicXYZ array

                                  • Use custom object with one volatile field and have an array of that object.

                                  • Use the ParallelArray of jsr166y addendum instead in your algorithm






                                  share|improve this answer


























                                    1












                                    1








                                    1







                                    Yes, as bad cache interleaving can still happen in a multi-cpu/core environment. There are several options to avoid it:




                                    • Use the Unsafe Sun-private library to atomically set an element in an array (or the jsr166y added feature in Java7

                                    • Use AtomicXYZ array

                                    • Use custom object with one volatile field and have an array of that object.

                                    • Use the ParallelArray of jsr166y addendum instead in your algorithm






                                    share|improve this answer













                                    Yes, as bad cache interleaving can still happen in a multi-cpu/core environment. There are several options to avoid it:




                                    • Use the Unsafe Sun-private library to atomically set an element in an array (or the jsr166y added feature in Java7

                                    • Use AtomicXYZ array

                                    • Use custom object with one volatile field and have an array of that object.

                                    • Use the ParallelArray of jsr166y addendum instead in your algorithm







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jul 15 '09 at 16:43









                                    akarnokdakarnokd

                                    49.4k9102150




                                    49.4k9102150























                                        1














                                        Since read() is not synchronized you could have the following scenario:



                                        Thread A enters write() method
                                        Thread A writes to nwriting = 0;
                                        Thread B reads from nwriting =0;
                                        Thread A increments nwriting. nwriting=1
                                        Thread A exits write();


                                        Since you want to guarantee that your variable addresses never conflict, what about something like (discounting array index issues):



                                        int i;
                                        synchronized int curr(){ return i; }
                                        synchronized int next(){ return ++i;}

                                        int read( ) {
                                        return values[curr()];
                                        }

                                        void write(int x){
                                        values[next()]=x;
                                        }





                                        share|improve this answer


























                                        • thanks, but not my question & your scenario can't happen (steps 2 and 3 would never occur)

                                          – Jason S
                                          Jul 15 '09 at 17:20
















                                        1














                                        Since read() is not synchronized you could have the following scenario:



                                        Thread A enters write() method
                                        Thread A writes to nwriting = 0;
                                        Thread B reads from nwriting =0;
                                        Thread A increments nwriting. nwriting=1
                                        Thread A exits write();


                                        Since you want to guarantee that your variable addresses never conflict, what about something like (discounting array index issues):



                                        int i;
                                        synchronized int curr(){ return i; }
                                        synchronized int next(){ return ++i;}

                                        int read( ) {
                                        return values[curr()];
                                        }

                                        void write(int x){
                                        values[next()]=x;
                                        }





                                        share|improve this answer


























                                        • thanks, but not my question & your scenario can't happen (steps 2 and 3 would never occur)

                                          – Jason S
                                          Jul 15 '09 at 17:20














                                        1












                                        1








                                        1







                                        Since read() is not synchronized you could have the following scenario:



                                        Thread A enters write() method
                                        Thread A writes to nwriting = 0;
                                        Thread B reads from nwriting =0;
                                        Thread A increments nwriting. nwriting=1
                                        Thread A exits write();


                                        Since you want to guarantee that your variable addresses never conflict, what about something like (discounting array index issues):



                                        int i;
                                        synchronized int curr(){ return i; }
                                        synchronized int next(){ return ++i;}

                                        int read( ) {
                                        return values[curr()];
                                        }

                                        void write(int x){
                                        values[next()]=x;
                                        }





                                        share|improve this answer















                                        Since read() is not synchronized you could have the following scenario:



                                        Thread A enters write() method
                                        Thread A writes to nwriting = 0;
                                        Thread B reads from nwriting =0;
                                        Thread A increments nwriting. nwriting=1
                                        Thread A exits write();


                                        Since you want to guarantee that your variable addresses never conflict, what about something like (discounting array index issues):



                                        int i;
                                        synchronized int curr(){ return i; }
                                        synchronized int next(){ return ++i;}

                                        int read( ) {
                                        return values[curr()];
                                        }

                                        void write(int x){
                                        values[next()]=x;
                                        }






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jul 15 '09 at 16:53

























                                        answered Jul 15 '09 at 16:45









                                        Steve B.Steve B.

                                        38.9k1181125




                                        38.9k1181125













                                        • thanks, but not my question & your scenario can't happen (steps 2 and 3 would never occur)

                                          – Jason S
                                          Jul 15 '09 at 17:20



















                                        • thanks, but not my question & your scenario can't happen (steps 2 and 3 would never occur)

                                          – Jason S
                                          Jul 15 '09 at 17:20

















                                        thanks, but not my question & your scenario can't happen (steps 2 and 3 would never occur)

                                        – Jason S
                                        Jul 15 '09 at 17:20





                                        thanks, but not my question & your scenario can't happen (steps 2 and 3 would never occur)

                                        – Jason S
                                        Jul 15 '09 at 17:20


















                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1132507%2fjava-array-thread-safety%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        MongoDB - Not Authorized To Execute Command

                                        in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                                        Npm cannot find a required file even through it is in the searched directory