Действительно ли Java примитивен ints атомарный дизайном или случайно?

Используйте свойство 'url' для [actions], чтобы переопределить URL по умолчанию.

$resource(url, [paramDefaults], [actions], options);

например:

$resource('http://localhost/pleaseGethere/:id',{},{
    getMethod:{
        method:'GET',
        isArray:true
    }
    postMethod:{
        url:'http://localhost/pleasePosthere',
        method:'POST',
        isArray:false
    }
}

Использование Angular $ resource: http://docs.angularjs.org/api/ngResource/service/$resource

41
задан JustJeff 17 June 2009 в 12:30
поделиться

4 ответа

All memory accesses in Java are atomic by default, with the exception of long and double (which may be atomic, but don't have to be). It's not put very clearly to be honest, but I believe that's the implication.

From section 17.4.3 of the JLS:

Within a sequentially consistent execution, there is a total order over all individual actions (such as reads and writes) which is consistent with the order of the program, and each individual action is atomic and is immediately visible to every thread.

and then in 17.7:

Some implementations may find it convenient to divide a single write action on a 64-bit long or double value into two write actions on adjacent 32 bit values. For efficiency's sake, this behavior is implementation specific; Java virtual machines are free to perform writes to long and double values atomically or состоит из двух частей.

Обратите внимание, что атомарность сильно отличается от волатильности.

Когда один поток обновляет целое число до 5, это гарантирует, что другой поток не увидит 1 или 4 или любое другое промежуточное состояние, но без какой-либо явной изменчивости или блокировки другой поток может навсегда видеть 0.

Что касается усердной работы, чтобы получить атомарный доступ к байтам, вы правы: виртуальной машине, возможно, придется очень постараться ... но у нее есть к. Из раздела 17.6 спецификации:

Некоторые процессоры не предоставляют возможность записи в один байт. Это было бы незаконно реализовать байт массив обновлений на таком процессоре просто читать слово целиком, обновление соответствующего байта и затем записать все слово обратно в объем памяти. Иногда эта проблема известный как разрыв слов, и на процессоры, которые не могут легко обновить один байт изолированно какой-то другой потребуется подход.

Другими словами, JVM должна сделать это правильно.

60
ответ дан 27 November 2019 в 00:21
поделиться

A read or write from integer or any smaller type should be atomic, but as Robert noted, longs and doubles may or may not depending on the implementation. However, any operation that uses both a read and a write, including all of the increment operators, are not atomic. Thus, if you have to threads operating on an integer i=0, one does i++ and the other does i=10, the result could be 1, 10, or 11.

For operations like this, you should look at AtomicInteger which has methods for atomically modifying a value while retrieving the old one or to atomically increment the value.

Finally, threads may cache the value of the variable and won't see changes made to it from other threads. To make sure that both threads always see changes made by the other thread, you need to mark the variable as being volatile.

4
ответ дан 27 November 2019 в 00:21
поделиться
  • No amount of testing can prove thread safety - it can only disprove it;
  • I found a indirect reference in JLS 17.7 which states

Some implementations may find it convenient to divide a single write action on a 64-bit long or double value into two write actions on adjacent 32 bit values.

and further down

For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half.

This seems to imply that writes to ints are atomic.

27
ответ дан 27 November 2019 в 00:21
поделиться

This is somewhat complicated, and is related to system wordsize. Bruce Eckel discusses it in more detail: Java Threads.

0
ответ дан 27 November 2019 в 00:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: