Questions in 1998

December 12, 1998

There's a common problem whereby Java programs using GUIs don't fully exit when the last window is closed and disposed. Has anybody tried retrieving a reference to the AWT thread and marking it as a daemon thread in order to get your application to auto-exit when all windows are closed and disposed? Did it work? If so how did you keep your application running after main() finished? Or have you come up with any other means, short of calling System.exit(0) to get your application to quit when the last window closes?

The answers

August 14, 1998

According to Sun, "The byte streams are synchronized on each stream object." (Ken Arnold and James Gosling, The Java Programming Language, 2nd Edition, p. 231) However, lately I've noticed that this doesn't actually seem to be the case for many stream classes, so today's question is: Just how thread safe are streams anyway?

Consider, for example, the readInt() method in java.io.DataInputStream


    public final int readInt() throws IOException {
    InputStream in = this.in;
    int ch1 = in.read();
    int ch2 = in.read();
    int ch3 = in.read();
    int ch4 = in.read();
    if ((ch1 | ch2 | ch3 | ch4) < 0)
         throw new EOFException();
    return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
    }

The individual calls to in.read() are atomic, but the complete readInt() method is not. What if a different thread interrupts this method after ch2 is read and before ch3 is read? Suppose further that the interrupting thread proceeds to read some bytes from this very same input stream. When this method begins executing again, the ch3 and ch4 that it then reads will have no necessary realtionto the ch1 and ch2 already read. Whatever data it reads must be considered corrupt.

This wouldn't be hard for Sun to fix, but it would have some performance implications. The easiest fix is to simply declare readInt() synchronized:


    public final synchronized int readInt() throws IOException {
    InputStream in = this.in;
    int ch1 = in.read();
    int ch2 = in.read();
    int ch3 = in.read();
    int ch4 = in.read();
    if ((ch1 | ch2 | ch3 | ch4) < 0)
      throw new EOFException();
    return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
    }

A slightly more robust alternative synchronizes the underlying input stream instead:


    public final int readInt() throws IOException {
      
      synchronized(this.in) {
        InputStream in = this.in;
        int ch1 = in.read();
        int ch2 = in.read();
        int ch3 = in.read();
        int ch4 = in.read();
        if ((ch1 | ch2 | ch3 | ch4) < 0)
         throw new EOFException();
        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
      }
    }

Neither of these is implemented in any current versions of Java I've seen. You could do something similar by wrapping a DataInputStream object inside your own stream class that provided the same interface but declared all methods synchronized.

This problem is most obvious in filter streams like DataInputStream and DataOutputStream, but it applies to any stream that needs to insure that related bytes are kept together.

So the question this week is really four-fold:

  1. Is there some thread safety constraint on stream methods I'm just not seeing?
  2. Is the behavior of streams in multi-threaded situtations documented anywhere? Even as a rule of thumb like "Never use the same stream in two different threads"
  3. Should stream methods be declared synchronized?
  4. Is there ever a good reason to use the same stream (other than System.out, System.in, and System.err) in two different threads?

I'm also looking for citations of anywhere Sun has said that the Java class library is guaranteed to be thread safe or anything like that. I do remember this being said, but I can't for the life of me find it anywhere. (It could have been part of an early white paper or tutorial that's no longer available.) Certainly if the class library isn't thread safe, then it's beholden on Sun to document exactly what isn't. (Vectors and enumerations in java.util are another common instance of non-thread safe classes.)

The answers

July 30, 1998

I still don't have my own copies of XML: Extensible Markup Language, but IDG did send me this small picture of the cover:

Near as I can make out that's a side-on view of a spiral galaxy, but I could be wrong.

IDG's official name for this series is "The Professional Series" but that's rather boring, and I don't think that name is used outside of IDG. Other books in the series include my own JavaBeans which has a picture of a nebula, Troy Downing's Java RMI, Bernard van Haecke's JDBC, and Daniel I. Joshi and Pavel A. Vorobiev's JFC: Java Foundation Classes. Cover pictures are below.

JavaBeans cover JDBC Cover JFC Cover Java RMI cover

What do you think this series should be called? Space books? Astrobooks? Hubble books? (All the cover pictures come from the Hubble Space Telescope) Something else? Send me your ideas. I'll post the best ones here, and send a free copy of XML: Extensible Markup Language to the person who submits the most creative, humorous, and/or original suggestion.

Responses

Sunday, July 19, 1998

Today's question comes courtesy of O'Reilly & Associates, publishers of Java Network Programming.

We all get 'em. We all hate 'em. Error messages are displayed messages that report errors to the user with a simple text message--a very simple text message. These tiresome error messages never seem to explain or help. Send O'Reilly your favorite (most irritating) error message and win books! It's simple. Send in your message (one per person) and Ben Ezzell, the author of Windows Error Messages, will choose the best three.

The three top prizes are:

  • 1st O'Reilly books valued to $150
  • 2nd O'Reilly books valued up to $75
  • 3rd O'Reilly books valued up to $40

Requirements
All entries should include:

  • "Error Message Contest" as the message subject.
  • The source of the error message (i.e., the application and version issuing the error).
  • How the error message was reached (i.e., what condition produced the message).
  • Why this error is inappropriate, confusing, or incorrect.

Contest ends 15 August 1998. Winners will be notified (and their error message posted) one week from contest closing date.

Please note that responses must be sent to Ben Ezzel, ben@ezzell.org, not to Elliotte Rusty Harold. Complete details at http://windows.oreilly.com/news/contest_0598.html

Tuesday, July 14, 1998

Who is javafaq.com? And what are they planning to do?

% whois javafaq.com

Registrant:
Planet Free (JAVAFAQ-DOM)
   8625 Carlin Avenue  N/A
   Sacramento, CA 95823
   US

   Domain Name: JAVAFAQ.COM

   Administrative Contact:
      Nghiem, Cuong  (CN994)  machina@JAVAFAQ.COM
      (916) 421-2709
   Technical Contact, Zone Contact:
      Host Master  (NETCOMI-WM)  domreg@NETCOMI.COM
      972-481-5700
   Billing Contact:
      Nghiem, Cuong  (CN994)  machina@JAVAFAQ.COM
      (916) 421-2709

   Record last updated on 24-Jun-98.
   Record created on 05-Aug-97.
   Database last updated on 15-Jul-98 04:19:47 EDT.

   Domain servers in listed order:

   NS3.NETCOMI.COM              204.58.155.18
   NS4.NETCOMI.COM              204.58.155.19
Responses
Tuesday, July 7, 1998

Today's question is of a different sort. I get some interesting email about general Java issues, particular news items, the quote of the day, and more. A lot of it's worth posting. Furthermore, there's obviously interest in a more interactive Cafe au Lait, as the enthusiastic response to the Question of the Day shows.

However, my time is severely constrained and I cannot afford more time to edit, format, and post reader comments.

What I think I need is a simple way to add discussion forums to this site. These would not be generic, ongoing forums on broad issues like comp.lang.java but specific forums related to individual quotes, news items, or questions. For example, this would allow you to discuss Mark Pesce's claim above that Internet tech that doesn't support the Mac is doomed to failure. What I have in mind is very roughly, the sort of discussions that take place at slashdot.org.

Here are my requirements for the forum software I envision, in rough order of priority:

  1. The software must run on Solaris and Apache. Unix and Windows solutions are useless to me.
  2. I have no direct income from this site. Cheap is good, free is better. Anything that crosses into four figures is out of the question.
  3. It must be almost trivial for me to create new forums. I should be able to set up a new forum in less than five minutes, preferably less than one.
  4. I am a firm believer in the value of moderated lists. I should be able to easily edit the forum pages, for instance to delete inappropriate posts.
  5. It should not require root access to install or set up the software. It must not require root access to moderate or edit the forums.
  6. It should use basic HTML and run in web browsers that do not support Java or JavaScript. I generally work on the site on a Mac, and find Java and JavaScript required sites to be nigh-on unusable. I do not have time to debug cross-platform idiosyncracies.
  7. It should not require registration for posting though it may allow it. I hate registration. I can't remember all the passwords I already have.
  8. Threading is not required. Each forum can be its own thread.

If you know of anything that meets these requirements, please send suggestions to me at elharo@ibiblio.org No free books today, but a successful answer will result in a more interesting and fun Cafe au Lait.

Responses

Friday, July 3, 1998

The Java standard convention for equals() methods is something like this:

  public boolean equals(Object o) {
  
    // make sure o has the right type
    if ((o != null) && (o instanceof ThisClass)) {
    
      check the state of the two objects to see if they're equal
      return true if they match, false if they don't
      
    }
	
    // The class didn't match so  
    return false;
  }

Looking through the Java source code, you find this idiom all over the place.

Now consider this equals() method:

  public boolean equals(ThisClass o) {
  
    // we know o has the right type o has the right type 
    // because of the method signature
    
    check the state of the two objects to see if they're equal
    return true if they match, false if they don't


  }

One of my students pointed out that a class using either of these signatures would have equivalent behavior. Suppose we have two objects, t1 and t2, and both are instances of ThisClass. Consider this statement:

boolean result1 = t1.equals(t2);

If ThisClass has the first equals() method, t2 passes the type check, and the two object are compared according to their state. If ThisClass has the second equals() method, t2 is passed to that method and the two object are compared according to their state. In either case the result is the same.

Now consider this statement:

boolean result2 = t1.equals(o);

If ThisClass has the first, standard equals() method, o fails the type check and the method returns false. If ThisClass has the second equals() method, the equals() method inherited from java.lang.Object is invoked instead. This equals() method tests for object identity and returns false.

Thus in all possible cases I can think of, the results are the same. You can look at more complicated interactions involving subclasses, but since all Java method are invoked dynamically (all methods are virtual in C++ terms) this doesn't seem to make a difference. So here's today's question:

Is there any good reason to prefer one variant of the equals() method over the other?

A free copy of JavaBeans goes to the person submitting the best answer received by Monday morning. I'll collect interesting answers and post them here as well. Previous questions can be found on this page.

Responses

Wednesday, July 1, 1998

Can anyone explain to me why show() is deprecated in java.awt.Component but not in java.awt.Window?

I'll post interesting responses here and send a free copy of JavaBeans to the person who submits the best answer by Thursday morning.

Responses


[ Cafe au Lait | Books | Trade Shows | Links | FAQ | Tutorial | User Groups ]

Copyright 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified December 12, 1998