Skip to Content
Java Network Programming, Second Edition
book

Java Network Programming, Second Edition

by Elliotte Rusty Harold
August 2000
Intermediate to advanced
760 pages
21h
English
O'Reilly Media, Inc.
Content preview from Java Network Programming, Second Edition

Returning Information from a Thread

One of the hardest things for programmers accustomed to traditional, single-threaded procedural models to grasp when moving to a multithreaded environment is how to return information from a thread. Getting information out of a finished thread is one of the most commonly misunderstood aspects of multithreaded programming. The run( ) method and the start( ) method don’t return any values. For example, suppose that instead of simply printing out the SHA digest as in Example 5.1 and Example 5.2, the digest thread needs to return the digest to the main thread of execution. Most people’s first reaction is to store the result in a field, then provide a getter method, as shown in Example 5.3 and Example 5.4. Example 5.3 is a Thread subclass that calculates a digest for a specified file. Example 5.4 is a simple command-line user interface that receives filenames and spawns threads to calculate digests for them.

Example 5-3. A Thread That Uses an Accessor Method to Return the Result

import java.io.*; import java.security.*; public class ReturnDigest extends Thread { private File input; private byte[] digest; public ReturnDigest(File input) { this.input = input; } public void run( ) { try { FileInputStream in = new FileInputStream(input); MessageDigest sha = MessageDigest.getInstance("SHA"); DigestInputStream din = new DigestInputStream(in, sha); int b; while ((b = din.read( )) != -1) ; din.close( ); digest = sha.digest( ); } catch (IOException e) { System.err.println(e); ...
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.
Start your free trial

You might also like

Java Network Programming, 4th Edition

Java Network Programming, 4th Edition

Elliotte Rusty Harold
Java Concurrency, 2/e

Java Concurrency, 2/e

Douglas Schmidt

Publisher Resources

ISBN: 1565928709Supplemental ContentCatalog PageErrata