01: /*
02: *
03: *
04: * Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
05: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License version
09: * 2 only, as published by the Free Software Foundation.
10: *
11: * This program is distributed in the hope that it will be useful, but
12: * WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14: * General Public License version 2 for more details (a copy is
15: * included at /legal/license.txt).
16: *
17: * You should have received a copy of the GNU General Public License
18: * version 2 along with this work; if not, write to the Free Software
19: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20: * 02110-1301 USA
21: *
22: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
23: * Clara, CA 95054 or visit www.sun.com if you need additional
24: * information or have any questions.
25: */
26:
27: package com.sun.midp.links;
28:
29: /**
30: * A thread that sends the given message on the given link.
31: */
32: class Sender extends Thread {
33: public static final long TIMEOUT = 1000L;
34:
35: Link link;
36: LinkMessage msg;
37: boolean done;
38: Throwable exception;
39:
40: /**
41: * Constructs a new Sender, starts its thread, and waits to give the new
42: * thread a chance to block in send().
43: */
44: Sender(Link newlink, LinkMessage newmsg) {
45: link = newlink;
46: msg = newmsg;
47: done = false;
48: exception = null;
49: start();
50: Utils.sleep(50);
51: }
52:
53: /**
54: * Waits until the thread finishes or until a timeout has expired.
55: */
56: public void await() {
57: long timeout = System.currentTimeMillis() + TIMEOUT;
58: synchronized (this ) {
59: try {
60: while (System.currentTimeMillis() < timeout && !done) {
61: wait(TIMEOUT);
62: }
63: } catch (InterruptedException ignore) {
64: }
65: }
66: }
67:
68: /**
69: * Sends a message and notifies when done, capturing any exceptions.
70: */
71: public void run() {
72: try {
73: link.send(msg);
74: } catch (Throwable t) {
75: exception = t;
76: } finally {
77: synchronized (this ) {
78: done = true;
79: notifyAll();
80: }
81: }
82:
83: completed(msg, exception);
84: }
85:
86: /**
87: * A completion callback. Called after the thread returns from the send()
88: * call. The msg parameter contains the message sent. The thr parameter
89: * contains any Throwable caught, or null there was none. This is
90: * intended to be overridden by a subclass. The default implementation
91: * does nothing.
92: */
93: public void completed(LinkMessage msg, Throwable thr) {
94: }
95:
96: }
|