O'Reilly logo

Java RMI by William Grosso

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Support for Threads in Java

Now that we’ve discussed why we need threads, and what sort of control we need over them, we can discuss how to use threads in Java. Java is almost unique among programming languages in that it has explicit, and fairly extensive, support for threading built into the language. This support is in three main forms:

  • A mutex variable is associated with every object. Java provides the synchronized keyword as a way to lock and unlock these mutex variables.

  • In addition, there is a set of methods defined on Object that support more finely grained coordination of related actions taken by threads.

  • A set of classes, defined in the java.lang package, that enables programmers to create new threads and manage their lifetimes.

Tip

There are other forms of support for threading in Java. One example is the volatile keyword. We don’t cover these other threading mechanisms because this is a chapter on threading, not a book on threading. The preceding forms of support constitute the core of what you need to know in order to write threadsafe code.

Objects Have Associated Mutex Variables

Every instance in a Java program has an associated lock, including class objects that are instances of java.lang.Class. In order to request a lock, you simply use the synchronized keyword, as in the following code snippet:

// declarations
Object foo;
// ....
synchronized(foo) {
// processing that occurs once the lock is granted
}

That is, you create a synchronized block by using the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required