EDITORIAL
As we all know, java.lang.String
like no forced synchronization code, but it is thread-safe, because it is an immutable class, its operations are returned each time a new String
object. Rational use of immutable objects can achieve lock-free
results.
Immutable objects most central places that do not give the opportunity to modify the external shared resources , so as to avoid data inconsistencies multiple threads because the competition for shared resources cause, but also lock-free
avoids the performance loss caused by locks.
ImmutableIntegerCounter
// final 修饰,不能继承
public final class ImmutableIntegerCounter {
// final 修饰,不允许其他线程对其更改
private final int initial;
public ImmutableIntegerCounter(int initial) {
this.initial = initial;
}
public ImmutableIntegerCounter(ImmutableIntegerCounter counter, int i) {
this.initial = counter.getInitial() + i;
}
// 每次调用 increment 都会新构造一个 ImmutableIntegerCounter
public ImmutableIntegerCounter increment(int i) {
return new ImmutableIntegerCounter(this, i);
}
public int getInitial() {
return initial;
}
}
test
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class ImmutableIntegerCounterTest {
private ImmutableIntegerCounter integerCounter = null;
@Before
public void init() {
integerCounter = new ImmutableIntegerCounter(0);
}
@Test
public void incrementTest() throws InterruptedException {
IntStream.range(0, 3).forEach(i -> new Thread(() -> {
int increment = 1;
while(true) {
int oldValue = integerCounter.getInitial();
int result = integerCounter.increment(increment).getInitial();
System.out.println(oldValue + "+" + increment + "=" + result);
assert (oldValue + increment) == result;
increment++;
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start());
TimeUnit.SECONDS.sleep(10);
}
}
Output
The output of the three threads are correct
0+1=1
0+1=1
0+1=1
0+2=2
0+2=2
0+2=2
0+3=3
0+3=3
0+3=3
0+4=4
0+4=4
0+4=4
Process finished with exit code 130 (interrupted by signal 2: SIGINT)