Scheduling multiple thread execution
TaskScheduler.java rev. February 1999 - A solution to scheduling synchronized execution of multiple threads using wait() and notify() in a monitor. I tested this with 200 threads of random duration with set rules for order of execution that caused up to 84 threads to run concurrently.
Synchronized FIFO queue for multiple input & output threads
ProducerConsumerFIFOTest.java rev. April 1999 - A modification of the ProducerConsumer example in the Sun Java tutorial to accomplish thread-safe queuing of input from and output to multiple threads. The queue is implemented as an array of integers. It blocks input when full, and output when empty. The constructor sets the length of the queue. Rewrite this easily for any object or primitive type.
Look up Amino Acids or DNA triplets
TwoWayLookUp.java March 2005 - Data dredging is often a bad thing, but perhaps not in the case of looking for DNA sequences that code for a particular peptide and vice versa. And if DNA/Amino Acid look-ups are being done tens of million times per day, you might want to hard code it, right? Here's one solution using Java alone, but without the overhead (or benefit) of the Java collections classes. TestDNALookUp.java and TestAALookUp.java are very simple tests of this potentially very useful data structure. Java doc is here .
Finds the sentences in a file, regardless of locale.
FileSentenceReader.java rev. Sept 2007 - Get a list of sentences out of a file, in sound i18n fashion. The single static method in this class reads individual sentences and returns an ArrayList of those sentences, regardless of language and locale. The javadoc is here.
A Table of Contents applet for frame-based site navigation
WebMenu.class and Link.class rev. Nov 1999 - Use a text file to index your site. This applet does the rest. Requires Java version 1.02 or above(the applet will not attempt to run on lower version clients). See this file for instructions on how to write the HTML and the text file used by the applet. Updated (a one-word change) to handle color problems due to fast CPU caching. Doesn't work with the AOL browser, but should work fine (now) with Netscape and IE browsers.
All the constructors and functions of the old java.util.Date
NewDate.java rev. May 1999 - This class just implements all the old java.util.Date methods and constructors, overcoming the reasons for deprecating so many of Date's methods and constructors. Subclasses GregorianCalendar, so NewDate expands on what Date did by enabling add() and roll() date-math methods from Calendar. See the javadoc description, or get the compiled NewDate.class here.
While the calendar classes and their formatters are dauntingly complex at first, they are fully functional. Try, for example, to set a date like Feb 30 in my internationalized version of Vanhelsuwé's date-selector bean. Best seen with Netscape as MSIE once again mysteriously produces a result that is just a little different from what I coded.
Generic Formatter/Parser for Number, Currency and Percent
PaddedDecimalFormat.java rev. August 1999 - DecimalFormat extended for easy right-justified and decimal-aligned formatting of decimal, currency and percent output. Can replace every reference to DecimalFormat in your code. Full international support for western locales. Javadocs are here. Compiled class adds about 5K to the 20K in the core java.text NumberFormat and DecimalFormat classes.
International Numeric Data Entry Component
NumericTextField.java rev. October 1999 - Here's how to prevent anything but numbers from displaying in an AWT TextField. This implementation allows plus or minus as the first digit, and just one decimal separator (usually comma or dot). Check out this test application, or see how it works in your locale by loading this applet. As the source code shows, you just subclass TextField and implement KeyListener. For some reason the API javadoc is a bit misleading: it's easier than you might think!
A Bean Counter's Decimal class, using double, long and NumberFormat
CurrencyDecimal.java rev. August 1999 - Release level 1.1 source code for a "bean-counter's" decimal class. Regardless of your locale or language, the methods in this class do all the parsing, formatting and rounding needed by bookkeeping applications, with exactly the number of decimal places required by the default (or the requested) locale.
For example, if the general ledger cash account has a balance of $2,865, the data typically would be stored as the long integer 286500. You could obtain formatters for the default US locale and the French locale like this:
CurrencyDecimal cd = new CurrencyDecimal(); // default locale
long balance = 286500;
Locale loc_fr = new Locale("fr","FR"); // French locale
CurrencyDecimal cd_fr = new CurrencyDecimal(loc_fr);
double francsPerDollar = 6.1463;
long balance_fr = cd_fr.roundInternalDouble(francsPerDollar * balance);
Now you can output the balances like this:
String output_us = "101 Cash - US "
+ cd.displayAsCurrency( balance, 20 );
String output_fr = " - FR "
+ cd_fr.displayAsCurrency( balance_fr, 20);
which gives output like this:
101 Cash - US $2,865.00
- FR 17 609,15 F
Whether you run this code in France or Brazil, it should give correct, localized numbers. Here is the compiled class. The documentation is here. But since numbers of type double are limited to 64 bits, CurrencyDecimal's floating point conversions will be off by a penny or so for amounts over $99 billion. If that's not good enough for your application, use BigCurrencyDecimal and BDFormat (below).
A Bean Counter's Decimal class, using BigDecimal, BigInteger and BDFormat
BigCurrencyDecimal.java rev. October 1998 - JDK 1.1 source code. Same basic functionality as the CurrencyDecimal class, but implemented for an application that uses BigInteger objects (rather than long integer primitive types) internally. At what I guess is a considerable cost in speed, you get no rounding problems and no maximum or minimum supported value, except the integer portion of any decimal to be formatted must be less than 20 digits due to a hard-coded limitation of the java.text package (as of JDK 1.2). Multiple instances will display (and decimals will align) across locales. Here is thecompiled class. And here is the documentation. The same example as shown above for CurrencyDecimal looks like this when coded for BigCurrencyDecimal:
BigCurrencyDecimal bcd = new BigCurrencyDecimal(); // default locale
BigInteger balance = BigInteger.valueOf(286500);
Locale loc_fr = new Locale("fr","FR"); // French locale
BigCurrencyDecimal bcd_fr = new BigCurrencyDecimal(loc_fr);
BigDecimal francsPerDollar = new BigDecimal(6.1463);
BigInteger balance_fr =
bcd_fr.roundInternalBigDecimal(
francsPerDollar.multiply( new BigDecimal(balance) ) );
String output_us = "101 Cash - US ........"
+ bcd.displayAsCurrency( balance, 20 );
String output_fr = " - FR ........"
+ bcd_fr.displayAsCurrency( balance_fr, 20);
The output is the same, of course, but the code runs about 3-fold slower (1,000 loops took 4.4 seconds on my P100 OS/2 set up) vs. 1.5 seconds for the CurrencyDecimal class. Note that BigCurrencyDecimal uses the parse() and format() routines from BDFormat (below) so both classes have to be
available to your application.
And now that IBM is offering a much improved BigDecimal class, there is a much smaller speed penalty for using BigDecimal. The new class, which IBM has asked Sun to include in a future version of Java, is not just faster, it is safer and much more robust. I have adapted BigCurrencyDecimal and BDFormat to use this new BigDecimal class, and indeed, it is much faster. Times are for 1,000 loops of the above code, not counting display time:
CurrencyDecimal using double and long............................1.596 sec
BigCurrencyDecimal using BigDecimal and BigInteger...............4.409 sec
BigCurrencyDecimal using com.ibm.math.BigDecimal and BigInteger..2.930 sec
If you have the 1.2 runtime, just put decimal.jar in your classpath, along with the path to rt.jar. Now you can use modified BDFormat.java and modified BigCurrencyDecimal.java . The compiled class files are modified BDFormat.class , BDFormatException.class , and modified BigCurrencyDecimal.class. The javadoc documentation is modified BDFormat javadocs and modified BigCurrencyDecimal javadocs.
To try out the new BigDecimal (and MathContext) class from IBM on your 1.1 runtime, you need the
decimal.jar file but you also need to create (or add) the java/lang/Comparable interface to the classes.zip file in JAVA11/lib. Or just get the decimal1.jar class and add it to your classpath.
BDFormat - a number formatter for BigDecimal objects
BDFormat.java rev July 1999 - JDK 1.1 source code for a locale-sensitive formatter/parser for the java.math.BigDecimal class. To get a locale-specific formatted string from a BigDecimal object "bd", for example, you can write:
String output = new BDFormat(locale).format(bd);
Or, to get the default locale's output formatted for six decimal places and using the common rounding mode, just write:
String output = new BDFormat().format(bd, 6, BigDecimal_ROUND_HALF_UP);
Parses locale-specific input into BigDecimal objects, or formats BigDecimals into numbers, currency or just plain decimals. You can specify the number of decimal places and a rounding mode for non-currency output (formatting). This class will accept input for parsing where the grouping separator is a space (as in French), unlike java.text.NumberFormat. Here are the compiled class and the exception class, and here is the documentation. What follows is a taste of the international capabilities of this class. (To take advantage of the new, faster BigDecimal class, you need the modified BDFormat code referred to under BigCurrencyDecimal above.)
Of course, it would be nice if NumberFormat and DecimalFormat supported BigDecimals as well as they support the other subclasses of java.lang.Number (Double, Float, etc.). Then you wouldn't need the above code in most situations. So Alan Liu and Mark Davis, the two IBM/Taligent programmers who put most of the java.text package together, have rewritten these classes and the internal DigitList class for full support of BigDecimal. There is now explicit support for rounding as numbers are formatted and the 18-integer-digit limitation is history. You can currently (summer '99) download their package from IBM's alphaWorks site. Hopefully these much improved classes will find their way into the core Java API real soon now, but they are definitely useable now.
Using Resource Bundles to Internationalize Java Code
TestRB.jar - JDK 1.1 code for a short command-line application, TestRB.class, that shows how to make Java programs portable from one language to the next, from one country to the next, and even from one time zone to the next. A resources package includes a group of classes that extend ListResourceBundle so the base class contains no hard-coded strings. Dates, numbers, and currency are dealt with in localized manner. About half of the classes in the java.text package are used in this test code. Source code is here . And Javadoc info is here.
How well does Java internationalize decimal numbers?
This Java 1.1 applet lists Java currencies and locales, giving a hint of how one can apply BDFormat, CurrencyDecimal and BigCurrencyDecimal to solve international number & currency formatting problems. If you have IBM's com.ibm.math package available, you can view the same applet (a bit quicker).
Converting Strings to Integers, Longs, Doubles and Vice Versa
NumberConverter.java is a stepping stone for people learning Java, and an argument for a new Java math using BigDecimal. The almost trivial methods in this class do four basic conversions: from string to integer or decimal, and from integer or decimal back to string. See the documentation for yet another exampe of what the BDFormat class(freeware) can do to help internationalize financial applications in Java.
Testing the Java version
TestVersion.java is a class with two methods that simply tell if the user's version is at least equal to some minimum version your code needs. The source code for class TestVersion includes a test routine, main(). Handles versions like 1.1.7A or 1.2B. Can even handle 1.2beta4 by disregarding whatever follows the word "beta". Why? A few web sites for some unknown reason are testing browser version in order to determine Java version, a big mistake. Here's some help if you have been doing this.
Given a Date object, show date/time in any Time Zone.
ExtDateFormat.java rev. March 1999 - Adds a method to SimpleDateFormat so any Date object can be displayed as the eqivalent date/time string for any available Java TimeZone ID. The format(Date, TimeZone) method should maybe be considered for a future version of Java.
Using long TimeZone ID's to implement "summer time" - a fix.
GMTZone.java rev. April 1999 - JDK
1.1 code that overrides TimeZone's getTimeZone() method to allow expected function of some of the long (more than 3-letter) internal TimeZone ID's. Make this class available to your code and change "TimeZone.getTimeZone(...)" to "GMTZone.getTimeZone(...)", and you may be able to plug in those long TimeZone ID's like "Europe/London." The GMTZone class includes some test code that illustrates how locale and time zone interrelate in Java. Here is the brief javadoc. Long TimeZone ID's are now reportedly supported in JDK 1.2 but if your code is going to run on release 1.1.x clients in the UK, Ireland, Portugal, or the Canary or Faeroe Islands, you will want to use this code.
Dayligt Savings or "Summer" Time for the GMT Time Zone
BSumTime.java rev. April 1999 - JDK 1.1 source code for a class that makes correct time and formatters available in UK locale during "British Summer Time" and year around. If you write for release level 1.1 clients, this may help. You may prefer to use my "fix" that allows the "Europe/London" and other long TimeZone ID's to work in the GMT meridian. This BSumTime class and methods are documented here. Code to test the BSumTime class and its methods is here. This shows how you can subclass SimpleDateFormat to simplify time zone and formatting when you internationalize your Java code. More info about UK summer time is available from the Royal Greenwich Observatory.
A Time Zone test utility
TZcheck.java rev. March 1998 - a java time zone tool. Compile and run on your machine to check your implementation in your locale and time zone. Lists all available time zone ID's as well as any other ID's at your offset from GMT. Or see this page for help if your set up is not getting the time right in Java.
Applying Rules to a Calendar
RuleCal.java rev. Sept 1999 - This one-method class shows how to extend GregorianCalendar to add methods that return Date objects based on rules. Here we just implement getting the first, second, last, etc. Tuesday, Saturday, etc. in a given month and year. You may want to add more functions. Test it with this class.
Subtract two dates
DateDiff.java rev. August 1999 - This is the kind of date-math code everyone expects to find, but doesn't. Provide two dates and get the difference in whatever unit, day, week, month, or year, you specify.
Permutations - a non-graphical measure of JVM performance
ShowPerms.java rev. November 1998 - Release level 1.02 source code that exercises your Java virtual machine and Runtime Release Level in a calculation-intensive way. The ".java" source file compiles to two classes that run from console/command-line. Together they show all the permutations for a set of integers, 1 to [size]. This, as opposed to drawing figures in a frame launched by an applet, is IMHO a valid way to benchmark your JVM and JDK. Compare your results with my P100 OS/2 results. The compiled classes are: ShowPerms.class and Perm.class. The documentation is here and also here.
How (and when) to use recursive method calls in Java
ArrayChange.java rev. May 1999 - Source code for the kind of useless and boring procedure we would write in Assembly in the early '80s for fun. Given a 2-D array of values, the task is to select a value to be zeroed, but also to change any equal-valued immediate neighbors in the array, as well as any neighbors of the neighbors, and so on recursively. The compiled classes are: ArrayChange.class and ArrayPoint.class. The documentation is here.
TextArea Word Wrap, even for Java 1.02
TextStuff.java April 1998 - This applet source code includes a method for wrapping text in java.awt.TextArea components. Java 1.02 event model and code (mostly). You can see TextArea word-wrap by running the applet now online.
The Java code above is written with a WORA (Write Once Run Anywhere) mentality. If any of it fails to run on your set-up, please let me know what happened! Other examples of Java code, applets and beans (millions of lines that you don't want to reinvent) are now indexed worldwide: Search JCentral from here. And if you want manufacturers to deliver Java-ready PC's when you go to the store, you will want to sign this petition.
How can I find the size of an entire directory? Rexx script for OS/2
DSZ.zip rev. Jan 1998 - a Rexx tool for finding those large deep directories full of stuff you don't really need. (This is written for OS/2 machines, so you may need to modify it for Unix or Windows.) You just need Rexx and the RexxUtil library,
for your platform.
What is the current window's VIO display mode? - C code for OS/2
getmode.c rev. Feb 1998. This is C code using the OS/2 API to get info about the current VIO Window display mode. The executable is here . Compiled with VisualAge for C++.
Solving Y2K in 1991 - assembler code for DOS
ATTCLK.SYS rev. Oct 1991. For the PC6300 and WGS computers, this 16-bit device driver in assembly language allows the Safari MM5874AN clock chip to recognize (synchronize to) dates in the 1980-2099 range, an improvement on the original 8 years from 1984-1991. Uses a parm in config.sys to initialize but loads only about 300 bytes of code into your DOS memory space. The documentation explains how to install and use this driver (in your museum piece).
The assembler code is well documented and shows how device drivers can be used to get around the hardware's limited calendar. In this case an 8-year clock chip was adapted to function acceptably over 120 years.