| Start |
|---|
| Pitfall: incorrect use of wait() / notify() The methods The "Lost Notification" problemOne common beginner mistake is to unconditionally call The reason this is wrong is that it depends on some other thread to call
The "Illegal Monitor State" bugIf you call (The design for Wait / notify is too low-levelThe best way to avoid problems with |
| Pitfall - Extending 'java.lang.Thread' The javadoc for the Using a custom thread class: Using a (Source: The custom thread class approach works, but it has a few problems: The approach of putting the thread logic into a With a lambda expression (Java 8 onwards), the above example would become even more elegant: |
| Pitfall - Too many threads makes an application slower. A lot of people who are new to multi-threading think that using threads automatically make an application go faster. In fact, it is a lot more complicated than that. But one thing that we can state with certainty is that for any computer there is a limit on the number of threads that can be run at the same time:
This tells us that simply creating more and more Java threads cannot make the application go faster and faster. But there are other considerations as well: Depending on the details of your application, these factors generally mean that there is a "sweet spot" for the number of threads. Beyond that, adding more threads gives minimal performance improvement, and can make performance worse. If your application create for each new task, then an unexpected increase in the workload (e.g. a high request rate) can lead to catastrophic behavior. A better way to deal with this is to use bounded thread pool whose size you can control (statically or dynamically). When there is too much work to do, the application needs to queue the requests. If you use an |
| Pitfall - Thread creation is relatively expensive Consider these two micro-benchmarks: The first benchmark simply creates, starts and joins threads. The thread's On a typical modern PC running Linux with 64bit Java 8 u101, this benchmark shows an average time taken to create, start and join thread of between 33.6 and 33.9 microseconds. The second benchmark does the equivalent to the first but using an As you can see, the averages are between 5.3 and 5.6 microseconds. While the actual times will depend on a variety of factors, the difference between these two results is significant. It is clearly faster to use a thread pool to recycle threads than it is to create new threads. |
| Pitfall: Shared variables require proper synchronization Consider this example: The intent of this program is intended to start a thread, let it run for 1000 milliseconds, and then cause it to stop by setting the Will it work as intended?Maybe yes, may be no. An application does not necessarily stop when the But that is actually not strictly true. In fact, the child thread will stop after it has observed The Java Language Specification guarantees that memory reads and writes made in a thread are visible to that thread, as per the order of the statements in the source code. However, in general, this is NOT guaranteed when one thread writes and another thread (subsequently) reads. To get guaranteed visibility, there needs to be a chain of happens-before relations between a write and a subsequent read. In the example above, there is no such chain for the update to the (Note to authors: There should be a separate Topic on the Java Memory Model to go into the deep technical details.) How do we fix the problem?In this case, there are two simple ways to ensure that the For a In addition to ensuring that there is mutual exclusion, the JLS specifies that there is a happens-before relation between the releasing a mutex in one thread and gaining the same mutex in a second thread. But isn't assignment atomic?Yes it is! However, that fact does not mean that the effects of update will be visible simultaneously to all threads. Only a proper chain of happens-before relations will guarantee that. Why did they do this?Programmers doing multi-threaded programming in Java for the first time find the Memory Model is challenging. Programs behave in an unintuitive way because the natural expectation is that writes are visible uniformly. So why the Java designers design the Memory Model this way. It actually comes down to a compromise between performance and ease of use (for the programmer). A modern computer architecture consists of multiple processors (cores) with individual register sets. Main memory is accessible either to all processors or to groups of processors. Another property of modern computer hardware is that access to registers is typically orders of magnitude faster to access than access to main memory. As the number of cores scales up, it is easy to see that reading and writing to main memory can become a system's main performance bottleneck. This mismatch is addressed by implementing one or more levels of memory caching between the processor cores and main memory. Each core access memory cells via its cache. Normally, a main memory read only happens when there is a cache miss, and a main memory write only happens when a cache line needs to be flushed. For an application where each core's working set of memory locations will fit into its cache, the core speed is no longer limited by main memory speed / bandwidth. But that gives us a new problem when multiple cores are reading and writing shared variables. The latest version of a variable may sit in one core's cache. Unless the that core flushes the cache line to main memory, AND other cores invalidate their cached copy of older versions, some of them are liable to see stale versions of the variable. But if the caches were flushed to memory each time there is a cache write ("just in case" there was a read by another core) that would consume main memory bandwidth unnecessarily. The standard solution used at the hardware instruction set level is to provide instructions for cache invalidation and a cache write-through, and leave it to the compiler to decide when to use them. Returning to Java. the Memory Model is designed so that the Java compilers are not required to issue cache invalidation and write-through instructions where they are not really needed. The assumption is that the programmer will use an appropriate synchronization mechanism (e.g. primitive mutexes, This has significant performance advantages for multi-threaded applications, but the downside is that writing correct multi-threaded applications is not a simple matter. The programmer does have to understand what he or she is doing. Why can't I reproduce this?There are a number of reasons why problems like this are difficult to reproduce: These things make bugs that are due to inadequate synchronization particularly difficult to solve. |
Read Article
https://develop.horje.com/learn/1434/reference