Managing Threads at Runtime
In addition to changing the running state of your application threads, the Java API allows you to do some basic thread management at runtime. The functionality provided includes thread synchronization, organization of threads into thread groups, and influencing the thread scheduler by setting thread priorities. Before we see how all of these can come into play in a distributed application, let’s go over them briefly so that we have a feeling for what kinds of capabilities they provide.
Synchronizing Threads
When you have multiple threads in an application, it sometimes becomes necessary to synchronize them with respect to a particular method or block of code. This usually occurs when multiple threads are updating the same data asynchronously. To ensure that these changes are consistent throughout the application, we need to make sure that one thread can’t start updating the data before another thread is finished reading or updating the same data. If we let this occur, then the data will be left in an inconsistent state, and one or both threads will not get the correct result.
Java allows you to define critical regions of code using the
synchronized
statement. A method or block of code is synchronized on a class,
object, or array, depending on the context of the
synchronized keyword. If you use the
synchronized modifier on a static method of a class, for example, then before the method is executed, the Java virtual machine obtains an exclusive “lock” ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access