Java Reference
In-Depth Information
In particular, when working with multiple threads, you must often take care to pre‐
vent multiple threads from modifying an object simultaneously in a way that might
corrupt the object's state. Java provides the
synchronized
statement to help the pro‐
grammer prevent corruption. The syntax is:
synchronized
(
expression
)
{
statements
}
expression
is an expression that must evaluate to an object or an array.
statements
constitute the code of the section that could cause damage and must be enclosed in
curly braces.
Before executing the statement block, the Java interpreter first obtains an exclusive
lock on the object or array specified by
expression
. It holds the lock until it is fin‐
ished running the block, then releases it. While a thread holds the lock on an object,
no other thread can obtain that lock.
The
synchronized
keyword is also available as a method modifier in Java, and when
applied to a method, the
synchronized
keyword indicates that the entire method is
locked. For a
synchronized
class method (a static method), Java obtains an exclu‐
sive lock on the class before executing the method. For a
synchronized
instance
method, Java obtains an exclusive lock on the class instance. (Class and instance
methods are discussed in
Chapter 3
.)
The throw Statement
An
exception
is a signal that indicates some sort of exceptional condition or error
has occurred. To
throw
an exception is to signal an exceptional condition. To
catch
an exception is to handle it—to take whatever actions are necessary to recover from
it. In Java, the
throw
statement is used to throw an exception:
throw
expression
;
The
expression
must evaluate to an exception object that describes the exception
or error that has occurred. We'll talk more about types of exceptions shortly; for
now, all you need to know is that an exception is represented by an object, which
has a slightly specialized role. Here is some example code that throws an exception:
public
static
double
factorial
(
int
x
)
{
if
(
x
<
0
)
throw
new
IllegalArgumentException
(
"x must be >= 0"
);
double
fact
;
for
(
fact
=
1.0
;
x
>
1
;
fact
*=
x
,
x
--)
/* empty */
;
// Note use of the empty statement
return
fact
;
}
When the Java interpreter executes a
throw
statement, it immediately stops normal
program execution and starts looking for an exception handler that can catch, or
handle, the exception. Exception handlers are written with the
try/catch/finally