Java Concurrent Topics

时间:2023-03-09 15:38:51
Java Concurrent Topics

To prevent Memory Consistency Errors(MCEs), it is good practice to specify synchronized class specifier, and mark all the related methods as synchronized. This solves the MCEs, but not perfectly in its inefficiency. Note if 2 methods marked synchronized in an instance, they cannot be running at the same time, however, in these 2 methods, not all the procedures are possible to get MCEs, so in some big & complex classes|methods, we use Atomic Variables instead as follows to cut the should be synchronized part into pieces (implements Compare and Swap + volatile and native) the cas method is not well working under intensive competitive:

 import java.util.concurrent.atomic.AtomicInteger;

 class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0); public void increment() {
c.incrementAndGet();
} public void decrement() {
c.decrementAndGet();
} public int value() {
return c.get();
} }

Concurrent Random Numbers:

In java.util.concurrent package, class ThreadLocalRandom, is constructed to use random numbers from multiple threads or ForkJoinTasks, use ThreadLocalRandom instead of Math.random(), to get better performance. If need cryptologilly safe, use SecureRandom class.

Call ThreadLocalRandom.current(); after that, call one of  the methods, nextX() to retrieve a random number. Every thread you need to instance a ThreadLocalRandom obj.

nextBoolean(), nextLong(), nextGaussian() ...

Further Reading in Java Concurrency:

  • Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea. A comprehensive work by a leading expert, who's also the architect of the Java platform's concurrency framework.
  • Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea. A practical guide designed to be accessible to the novice.
  • Effective Java Programming Language Guide (2nd Edition) by Joshua Bloch. Though this is a general programming guide, its chapter on threads contains essential "best practices" for concurrent programming.
  • Concurrency: State Models & Java Programs (2nd Edition), by Jeff Magee and Jeff Kramer. An introduction to concurrent programming through a combination of modeling and practical examples.
  • Java Concurrent Animated: Animations that show usage of concurrency features.