Java Reference
In-Depth Information
This
call()
method returns an
Integer
. (Note that we have conveniently used
the autoboxing support in J2SE 5.0 to have the
int
literal 1 automatically boxed
into an
Integer
return value.)
Getting the return value from a
Callable
depends upon the new generics
feature:
FutureTask
<
Integer
>
task
=
new FutureTask
<
Integer
>
(new
MyCallable ());
ExecutorService es
=
Executors.newSingleThreadExecutor ();
es.submit (task);
try
{
int result
=
task.get ();
System.out.println (
"
result from task.get ()
="
+ result);
}
catch (Exception e)
{
System.err.println (e);
}
es.shutdown ();
Here, we use the
FutureTask
class that supports an
Integer
return value.
Then the task is submitted using the
ExecutorService submit()
method,
and the result is obtained from the
FutureTask get()
method, again using
auto-unboxing to convert the
Integer
to an
int
. See the API documentation
for more information on
ExecutorService
, and
FutureTask
.
10.8.3 Other concurrency enhancements
Other enhancements in the
java.util.concurrent
package not discussed
here include advanced synchronization techniques, atomic types, and new
high-performance thread-safe collections
ConcurrentHashMap
,
CopyOn-
WriteArrayList
, and
CopyOnWriteArraySet
. See the API documentation
for more information on these new collections and other features.
10.9 Enumerated types in J2SE 5.0
Until Release 5.0, Java did not have a facility like the
enum
of C and C
.
In those languages,
enum
is used to create a set of named integer values to
use as constants. This helps prevent accidentally using an illegal value where a
group of predefined constant values, and nothing else, is expected. We've seen
a related feature in
BorderLayout
's constants
NORTH
,
SOUTH
,
CENTER
, etc
(see Chapter 6). Those constants are just
final static Strings
, and it is
perfectly permissible, though not advisable, to pass in literal
Strings
when
using a
BorderLayout
. Doing so is not advisable because a misspelled string
literal (“north” instead of “North”, for instance) is not interpreted as you hoped.
++
Search WWH ::
Custom Search