Wednesday, 24 December 2008

Basic Mathematics in Java

The public final class Math contains all the basic numerical functions and constants.

Math.E (the base of the natural logarithms), Math.PI (ratio of circumference of a circle to its diameter).

Math.ceil, Math.floor do the expected operations, mapping doubles to ints.

Math.random, when first called creates a new PRN generator (thread-safe singleton, java.util.Random). If numerous threads are involved, multiple PRN generators ought to be instantiated. Returns a double value in the range [0,1).

Beware of the int division wall. This basically means 1/5 returns 0 since int/int returns floor(int). To avoid the "int division wall" cast to double, use decimals or write 1.0/5 to get result of division as a double.

Monday, 15 December 2008

The King of Swing

J2SE 5.0 brought in some new Swing changes.
  • Default theme is Ocean
  • New "Synth" customizable L&F (javax.swing.plaf.synth)
  • Apply a "policy" to JTextArea (to update position of caret even if updates don't occur on EDT)

Saturday, 13 December 2008

The JGoodies Animation Framework

This Java animation framework uses concepts from the W3C SML ("Smile") specification, an XML language for interactive multimedia presentations. SMIL 3.0 has recently been published (December 2008).

A key concept in the JG framework is an animation function f(t) that maps TIME to values of an attribute of an ANIMATION TARGET. e.g. within 10s the radius of a circle doubles in size at constant rate. Animation functions are continuous over time, hence a rendering system can display an animation over different frame rates and maintain the gist of the motion.

The base package is com.jgoodies.common.animation. The AnimationFunction interface maps long time values to Java objects.

Eclipse Jargon Revealed

Any user of Eclipse is exposed to a vast amount of jargon. This is a quick guide to decrypting this jargon.

BIRT - an Eclipse-based reporting system for web applications. Birt stands for Business Intelligence and Reporting Tools. Here are some examples including a Camtasia studio screencast. (Lotus produced some of the earliest screencasting software in 1994).

Wednesday, 10 December 2008

Exceptions to Java java.lang.Exceptions

The compile error: "unreported exception java.lang.Exception; must be caught or declared to be thrown" forces you to add a throws clause to a method that can throw an exception.

That's not the end of the story. If this class overrides an interface method, the throws clause must be declared at the interface level. Using Eclipse compiler it gives: "Exception is not compatible with throws clause in Interface.method()". Using Sun compiler you get a slightly different message but the intent is the same. Irritating.

What next in Java 7?

Good article on adding closures to Java. An interesting comparison is made between closures and inner classes. The article is by Angelika Langer. Closures are a very beautiful way of implementing mathematics. For example, a bisection algorithm can be elegantly implemented with closures.

To understand the limitations of inner classes versus closures we need to understand exactly the rules for inner classes in Java. An inner class can just a private class inside another class (like an embedded struct). Anonymous inner classes are used when creating ActionListeners e.g. button.addActionListener( new ActionListener() {} ).

Sunday, 7 December 2008

The Dichotomy of Mutable and Immutable in Java

String and StringBuffer are immutable and mutable analogues of one another. StringBuffers are used to implement the binary string concatenation operator.

Example: x = "a" + "b" + "c";
is compiled to x = new StringBuffer().append("a").append("b").append("c").toString();

You can also call append on ints, chars, floats and doubles.

When you instantiate a StringBuffer it has an initial capacity of 16 characters, however e.g. new StringBuffer(500) will create a StringBuffer with an initial capacity of 500 characters.

An interesting article on a mutable and immutable design pattern (as exemplified by String and StringBuffer) can be found on javaworld.

Java 6 Platform Overview

http://java.sun.com/javase/6/docs/

A very interesting tool that comes with Java 6 is the VisualVM. Details of how to run it are here.

And here is a getting started guide to VisualVM.

Saturday, 6 December 2008

Java Server Development with java.net

java.net.ServerSocket is a class for implementing server sockets. ServerSockets can be created unbound, or bound to a particular port. In either case, the constructor may throw an IOException, which may be thrown when attempting to open the socket. The most important method on a server socket is accept(), which listens for a connection to be made to the socket and accepts it. Example code (notice the interplay between the ServerSocket and Socket classes):

import java.net.ServerSocket;
import java.net.BindException;

ServerSocket listenSocket = null;
try {
listenSocket = new ServerSocket(serverPort);
while(true) {
// listen for and accept incoming connection
Socket clientSocket = listenSocket.accept();
// do something
}
} catch (BindException bindEx) {
// error message to say server is already running on serverPort
System.exit(0);
}

The socket class abstracts the concept of an endpoint of communication between two machines. A nice visual analogy of the socket idiom is the probe-and-drogue method of aerial refuelling used by the USAF. Pictures can be seen on aerospaceweb.

SSLServerSocket is a special instance of ServerSocket; these sockets aer generally created by an SSLServerSocketFactory.

Tactics for Analysing Complex Java Code

Complex Java code can be analysed quickly using the following methods.

1. Create a temp file with the code in Visual J# Express. Compress the code, refactor logically.
2. Use the program and get an idea of how it works: inputs and outputs.
3. Identify critical control paths, frequently used and unused areas of the code. (perhaps only 20% of the code is actually interesting or relevant).
4. Write up the program in Python-style pseudocode.
5. Use set theory concepts (e.g. partitions) to break up the code into mutex sections (e.g. partitions of the input space, partitions of inner classes etc).

Basics of HashMap

HashMap is an unsynchronized hashtable which permits null values. It extends the AbstractMap class, which is a partial implementation of the Map interface.

Methods inherited from Map include:

Object get(Object key)
Object put(Object key, Object value)
void putAll(Map t) - copy all mappings from t
Object remove(Object key) - returns previously associated value or null

To access the collection of keys and values in a Map, the interface declares the following methods:

public Set keySet()
public Collection values()

To iterate through the keys of a HashMap you can do:

final Iterator mapIterator = map.keySet.iterator();
while (mapIterator.hasNext()) {
final String key = (String) mapIterator.next();
final CustomType value = (CustomType) map.get(key);
}

HashMap provides constant-time performance for its basic operations (get and put) i.e. RETRIEVAL and INSERTION, assuming the hash function distributes the elements properly among the buckets.

Basics of gnu.getop

A Java port of GNU getopt based on C getopt() functions in glibc. Getopt partitions the inputs to the command-line program into optional and non-optional inputs.

import gnu.getopt.Getopt;

Getopt g = new Getopt("porridge", (String[]) args, "a:b:c:");
g.setOpterr(false); // we'll do our own error handling

while((c=getopt())!=-1) {
switch(c) {
case 'a': _alpha = g.getOptarg(); break;
case 'b': _beta = g.getOptarg(); break;
case 'c': _gamma = g.getOptarg(); break;
}

Once these options are processed, the next phase is to process non-optional arguments.
A summary of useful methods on Getopt object:

g.getopt() - returns the current option passed to the command-line
g.getOptind() - returns the NEXT index in ARGV of the next element to be scanned (non-optional argument)

Friday, 5 December 2008

IntelliJ Keyboard Shortcuts

IntelliJ is a very fast editor from jetbrains and does remote debugging more than twice as fast as Eclipse. Searching is also slicker than Eclipse. Here are some handy shortcuts for jet-setting across your source code.

Cntrl-N Jump to class
Cntrl-E Scroll through open files
Cntrl-F and F3 Search and repeat last search
Cntrl-F12 Jump through class (fields and methods)

Alt-F7 Find usages (also click "Open in new tab" to get tabbed search)
Alt-left, Alt-right Scroll through panes (Cntrl-E if you want to jump >1 step at a time)
Cntrl-B Jump to DECLARATION
Cntrl-Alt-B Jump to IMPLEMENTATION

Alt-3 go to Find screen

The Cntrl-MouseUp/MouseDown combination can be used to dynamically zoom in/out of the current pane. This is the same key combination in Internet Explorer for the same operation.

The founder of JetBrains is Sergey Dmitriev whose hobbies include pure mathematics, including functional analysis. here's an interview with him. Official bio is here.

Thursday, 4 December 2008

Basics of java.lang

rt.jar contains a lot of the core Java classes, such as those in java.lang, and java.net. When learning the core classes think of what each one is and what they are used for. Try and think of at least three examples in each case (use Google code search to help you).

Examples:

java.lang.Character (implements Serializable, Comparable). Character is a wrapper for a char. Useful e.g. when processing a character input from stdin or from gnu.getopt. Characters can be converted to strings using toString().

java.lang.System (extends Object). This fundamental class contains sytem-wide operations that act on the currently running virtual machine.

  • Exit the VM. exit(statusCode) terminates the VM. A value other than zero indicates abnormal termination
  • Bring in code from a shared library. static void load(String filename), static void loadLibrary(String libname)
  • Garbage collect. System.gc() prompts the VM to run the garbage collector.
  • Reference std input, stderr and stdout. This is done via the static PrintStream fields System.in, System.err and System.out
  • Restrict sensitive operations. This can be done by creating a SecurityManager and calling setSecurityManager on the System class.

java.lang.System is the moral equivalent of java.lang.Runtime; both classes facilitate interaction with the currently running VM. Many methods on System e.g. System.gc, can also be called on the Runtime class, e.g. Runtime.gc.

Coding Conventions - Lower Camel Case and Upper Camel Case

Java generally uses "lower camel case" (LCC) for method names. Example: br.readLine();
C# generally uses "upper camel case" (UCC) for method names. Example: sr.ReadlLine();

This is also reflected in the use of "main" in Java and "Main" in C#.

Strings are represented by "class String" in both Java and C#. The difference is in C# String is aliased to string which is more natural to use and similar to C++.

One of the earliest commercial examples of camel case is the 1950s CinemaScope film projection system.

Old School java.io

Java's BufferedReader extends the abstract Reader class, which reads character streams.

import java.io.BufferedReader;
import java.io.FileReader;

try {
BufferedReader br = new BufferedReader( new FileReader( someFile ) );
while ( br.ready() ) {
String line = br.readLine();
// processLine(line)
}

br.close();
} catch (Exception e) {}

read() will read one character, readline() will read a line. Don't forget to close the reader when you're done. The BufferedReader has two constructors, one that takes a "regular" Reader object, and the other that takes a Reader and the size of the buffer.

Tuesday, 2 December 2008

To sun.misc.Signal or not sun.misc.Signal?

In Java an application can install its own signal handler via sun.misc.Signal. This is deprecated in Java 1.6.

http://www.ibm.com/developerworks/java/library/i-signalhandling/

Sunday, 30 November 2008

Java New IO: ByteBuffers

java.nio.ByteBuffer. Provides a range of operations:

get, put - read and write single byte, wrap - wraps a byte array into a buffer.



ByteBuffer is derived from the abstract class Buffer (aka java.nio.Buffer). "A buffer is a linear, finite sequence of elements of a specific primitive type". Properties include: capacity (number of items it contains, never negative and never changes), limit (index of first element that should not be read or written), position (index of next item to be read/written).

A byte buffer can be direct or non direct. Given a direct byte buffer, the JVM will do its best to do native I/O operations on it. This will avoid copying buffer's content to an intermediate buffer before invoking the O/S underlying I/O operations. There is a factory method allocateDirect(int capacity) that allocates a new direct byte buffer. If the capacity is negative we throw IllegalArgumentException.

Messaging Concepts (JMS etc)

JMS.

JMS is a layer on top an underlying messaging engine. JBoss, for example, has a messaging engine that implements the JMS specification, allowing transparent access to the messaging system.

Tibco.

Tibrv class has static open and close methods to create and destroy a Tibco "environment". getVersion returns the current version of Tibco for Java as a String. defaultQueue accesses the default queue (every process has exactly one default queue which you must not destroy).

Your RV client application can connect to a network service via a TibrvRvdTransport object that connects to an rvd (RV daemon process) or a TibrvRvaTransport which connects to an rva (RV agent process) that in turn connects to an RVD. The critical question -How does an RVD work? Basically, a program sends a message and RVD transmits it across the network. It sends messages with matching subject names to the appropriate listeners. (RVAs are used as intermediaries between RVDs and applications - precluding the need for Tibco (JNI) shared libraries to be installed on the client machine). They are used as a communication mechanism for Java applets to talk to Tibco machinery. RVAs add an extra level of indirection and are thus not as efficient as talking directly to a RVD. The RVD is basically a software router.

(note: If a transport can't connect to an rvd transport process it will automatically start one.)

Property Management in Java (-D option)

System.getProperty is a static method on the System class that takes a (String) key and returns a (String) value. Standard system properties include java.home (where Java is installed) and java.class.path (the Java classpath) and os.name and os.version.

System properties are set on startup using the -D<key>=<value> option. These properties may need to be set in a launch script to a Java program.

Properties can also be maintained in an external file. Then you call System.getProperties to get a reference to the Properties object (that inherits from Hashtable). The Hashtable methods put and putall can be called on the object but their use is strongly discouraged in favour of the method setProperty which allows you to set String keys and values (i.e. it enforces a type-constraint on the keys of the Properties object).

Properties can be maintained in an external file and then setProperty can be used to add them to the application's properties table. Some people like to write singleton managers for properties so access can be centralised and controlled (and type-constraints enforced) for System properties.

The Idiosyncracies of the Java VM Shutdown Sequence

JVM shutdown is in two parts.

  1. All registered shutdown hooks
  2. All uninvoked finalizers are run

Runtime.getRuntime().addShutdownHook(Thread) registers a new VM shutdown hook.

A shutdown hook is simply an "initialized but unstarted thread". When VM shuts down, it starts all shutdown hooks and runs them concurrently. Then it will run all uninvoked finalizers(assuming finalization-on-exit has been enabled).

Once shutdown has been initiated it can only be stopped by invoking the halt method, to forcibly terminate the JVM. halt has one argument which is status code. Any non-zero value indicates abnormal termination.

Read more in the Runtime (singleton) class documentation below:

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html

Wednesday, 26 November 2008

Java and Eclipse Shortcuts

Eclipse

Cntrl-Shift-T find Type

Cntrl-L Goto line
Cntrl-B Build

F3 jump to definition

Alt-Enter - File properties (file path, size, file encoding)

Set up different workspaces for "test projects" versus "real projects".

Configuring Eclipse to reference Existing Code

1. Set up a new workspace (different from the source location)
2. use the existing location for the code
3. create projects for specific parts of the code you want to change

Select "autoconfigure JRE and project layout based on source".

Switching Tabs in Eclipse

Control-Tab in Windows applications is replaced by ALT-LEFT and ALT-RIGHT, and Control-F6. Since control-tab is used so frequently it is easy to forget this Eclipse peculiarity.

To override this shortcut, do Windows->Preferences->General->Keys. Then replace "Change Next Editor" from Control-F6 to Control-tab. Sanity at last.

Cntrl-E is another useful way to bring up "Editor List" that allows explicit window switching.

Java

javap -c Disassemble a class file

Friday, 21 November 2008

Power of JFlex and CUP in Combination: LALR PArsers for Java

As a Java open source junkie you will have almost certainly have heard of JFlex and CUP but not really delved deeply into it, right? Here's a rapid sommaire of the two technologies.
  • JFlex (a rewrite of JLex) is known as the "fast scanner generator for Java".
  • CUP (no, not Cambridge University Press, but "Construction of Useful Parsers") is an LALR parser generator for Java. Rusty on ye olde Dragon Book basics? To remind you, LALR is lookahead LR parsing. LR parsing means the parser reads the input Left to right, and produces a Right-most derivation (LR is a general form of shift-reduce parsing, starting from the leaves of a tree and working up to the root - in computer science trees grow downwards from the root!). When referring to LALR(k) the k is the lookahead value. LALR is quite popular since it results in smaller parsing tables than canonical LR tables (Dragon Book Ch4, Syntax Analysis).
CUP user's manual states it is very similar to YACC, only it is written in Java, uses specifications with embedded Java and produces Java-implemented parsers. Think of CUP as YACC with a Java jacket and Java insoles. YACC was created by Stephen Johnson of AT&T, an article by the inventor can be found on the dinosaur.compilertools.net webpage. Parser generators like YACC are described in 4.9 of Dragon Book. Worth reading just as background to using CUP. YACC stands for "Yet Another Compiler Compiler" reflecting the parser generator mania of the 1970s.

Classgen is a related technology from the Technical University of Munich. It generates classes in the Visitor style. This page gives a good idea of what specifications look like in Classgen and what it can do. The whole area of creating computer programs based on computer specifications is extremely fascinating. Let the computers do all the hard programming and let humans customize the color schemes of the resulting software.

Speed Reading Java Open Source Code

Requires more than a passing knowledge of Java knowledge, APIs and standard open source components (par exemple, gnu.getopt).

Monday, 17 November 2008

Navigating Ganymede using Awesome Child-Oriented Fonts like Comic Sans - Makes Reading Java More Fun!

Making your way around Eclipse ain't easy when you're used to MSVC-style GUIs, so here's a primer on how to get things configured double-speedy in the old Ganymede release of Eclipse.

Change Font Size. This should not be difficult but for first-timers it's a super-sized sudoku puzzle.

Windows->Preferences->General->Appearance->Colors and Fonts. Click on the right category e.g. Java editor text font. Set a good font and size. Changing your font regularly keeps code-reading interesting.
  • Jokeman is a fun font to liven up boring code.
  • Kartika9 is very clear and well-spaced.
  • Vivaldi is beautiful and elegant but suffers from lack of readability.
  • Mistral makes Java look beautiful.
  • ComicSansMS is a nice, friendly readable font, classified as "casual, non-connecting script", a "child-oriented font" in the words of its inventor, Vincent Connare, who designed it for children's software. To quote an esteemed computer philosophe, "The real art of discovery consists not in finding new programming languages, but in seeing with new fonts".
  • Gill Sans MT is another "soft font" described as a "humanist" font, created by Eric Gill in 1927 and very popular in logos for media companies (e.g. BBC). Eric Gill received the accolade "Royal Designer for Industry" (Gill9 looks fine).

Show Line Numbers: W->P->G->Editors->Text Editors->Show line numbers

Saturday, 4 October 2008

Web Start and Click Once in Web Application Fisticuffs

Presenting Click Once, dubbed Microsoft's "Webstart rip-off", but actually looks smoother and more shiny than Web Start:

http://decav.com/blogs/andre/archive/2007/08/25/live-updating-line-graph-in-wpf.aspx

Saturday, 27 September 2008

Super-Power Synchronisation in Java and C#: Say Arrivederci to the Ornamental Garden Problem and Buonasera Deadlock!

In Java you would use a synchronised block. In C#, the syntactic shortcut lock does the same thing.

lock(x), where x is a reference type, is equivalent to

System.Threading.Monitor.Enter(x)
try {
...
} finally {
System.Threading.Monitor.Exit(x);
}

except that x is only evaluated once. Locking avoids problems like the ornamental garden problem. C#'s System.Threading namespace has stuff for COM interoperability which Java doesn't have e.g. the the System.Threading.ApartmentType to determine if an apartment is STA or MTA.

Wednesday, 24 September 2008

Is Java GC really better than C# GC? NO WAY! Java just hints, C# actually DOES stuff!

JAVA way: System.gc() -> Runtime.getRuntime().gc() - this is just a "hint" to JVM to do some cleanup
C# way: GC.Collect() -> this is a "command" to CLR, "clean up your act!" This will run all eligible object finalizers on a separate thread. Another important method is GC.WaitForPendingFinalizers, usually you call this after a GC.Collect. It makes a difference to the memory used by your program! You can also run a GC.Collect on a specific generation (generation 0 being the most recently allocated objects).

Thursday, 11 September 2008

Why Java Math Beats C# Math (Prime numerology)

Now if Java's integers don't have enough juice for you (and you must be a serious arithmetic junkie if that's the case) there is always refuge in java.math's BigInteger class.This is a perennial favourite if you want to test prime numbers. AFAIK prime numbers don't exist in C#, but hobbyists have nonetheless tried to find them using BigInteger code on codeproject.OK, partner! Let's instantiate java.math.BigIntegers! Let's find primes! To Double.POSITIVE_INFINITY and beyond!

Saturday, 6 September 2008

IEEERemainder: Simply the Best and Probably the Most Under-used method in java.lang.math

java.lang.Math's Math.IEEEremainder( double, double) rocks and rules! Forget about those boring and simple min, max and trig functions! Every Tom, Dick and Harry knows that. (Well, trig functions are not so simple in that they use Taylor series, but that's not too hardcore for a vaguley mathematical computer programmer). IEEERemainder is so cool that C# implements EXACTAMUNGO the same method in the System namespace of mscorlib. They copied the signatures cleanly right down to the name of the static class. Microsoft really did their homework on this one.

But whose implementation is faster? Haven't a clue what I'm talking about? Take a crash-course on math co-processors by talking to Dr Chuck. Now, THAT's what I'm talking about.

Saturday, 9 August 2008

The Clob Interface

Don't put SQL (Advanced) + JDBC (Expert) on your resume if you don't know what a Clob is.

What does the Class Class implement and extend?

This refers to java.lang.Class. Here's the declaration:

public final class Class
extends Object
implements Serializable

To print out the class name of an object you can do:

obj.getClass().getName()

Another common sight is calling the static method forName which returns the Class object (a.k.a. runtime class descriptor) associated with the given string name. By default, forName uses the class loader of the current class. If the class cannot be found, a ClassNotFoundException is thrown. forName can also throw a LinkageError and ExceptionInInitializer error.

In order to return the class object (or class descriptor) the class needs to loaded, linked and initialized. Thus Class.forName is sometimes used just to load and link a class then throw away the returned object.

The Class Class also contains boolean methods like isInterface and isPrimitive.

Friday, 8 August 2008

What is Dependency Injection?

Dependency injection (DI) is a specific form of Inversion of Control (IoC).

Programs utilising IoC are much harder to reason about than straightforward sequential programs.

Thursday, 7 August 2008

Hacking Java DB

Introduction to Java DB

Java DB is a pretty mature technology, that evolved out of IBM Cloudscape.
I like it better than some of the other offerings out there like HypersonicDB.

Java DB 10.4 using JDBC4 has a documented API and developers guide.
It uses an Apache 2.0 license. If you need to recap what JDBC 4.0 is all about, here's an old article on Artima.com with explanations.

To verify Derby has been properly installed on your system use the sysinfo tool.

java org.apache.derby.tools.sysinfo

should return your Java version, vendor and other configuration information.

Getting started with Java DB using ij

ij is the interactive Java tool for querying Derby. To test it out create and connect to a new database as follows.

ij> connect 'jdbc:derby:MyDbTest;create=true';
ij> exit;

This creates a directory MyDbTest and a file derby.log. Now you can connect to the new database:

ij> connect 'jdbc:derby:MyDbTest';
ij> show schemas;

will show all the schemas in the database e.g. APP, SYS, SQLJ.

Aliasing Makes Life Easier

Tip: to make the shell automatically recognise the Derby protocol, you can alias ij to the following:

alias ij="java -Dij.protocol=jdbc:derby: org.apache.derby.tools.ij"

See how easy this makes creating and connecting to a database:

connect 'TestDb;create=true';
connect 'TestDb';

Brilliant!

Note: -D is the standard way to set command-line flags in ij. If you have more than one flag to set, just do -D multiple times.

Embedded and Client-server Mode

Derby has both an embedded and client-server mode. In embedded mode, a Derby database may not be used concurrently between two VMs.

Semantics of java -jar

When we run jar files we can do so using java -jar. But what are the implications of this on classpath etc.?

The JAR (Java ARchive) file will contain a Manifest stating where the main method is located. JAR files provide compression for efficient storage.

What does JNI work? If I have a C++ library how do I access that from Java?

Sheng Liang has written a book on JNI divided into three parts:
The Programmers Guide should be read carefully.

Know - what is the JNIEnv interface pointer, what is the CPointer class and CMalloc class.

What is JPA?

JPA = Java Persistence API, standardises persistence and ORM in Java (integrates approaches from the Hibernate ORM library, JDO and Oracle's TopLink).

JPA is implemented in the GlassFish application server, from code contributed by Oracle.

Wednesday, 6 August 2008

How does ant build Java code?

JDK code samples can be built either with NetBeans or ant (ant.apache.org) using the build.xml file. A similar tool called nant is used for .NET.

How does Eclipse build Java code?

Eclipse has its own Java compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.

Compliance level can be checked using Alt-WP and clicking Java->Compiler.

Compiler->Errors and Warnings allows you to fine-tune what the compiler regards as error versus a warning. e.g. in my setup: non-static access to a static member is a warning, undocumented empty block is ignored.

The compiler is part of the JDT (Java development tools) extension to the workbench. It is not possible to use another Java compiler other than the built-in one (which includes support for special features like automatic incremental compilation and code snippet evaluation).

A programmers guide to JDT tooling can be found here.

What is the invokespecial JVM instruction?

invokespecial and invokevirtual are two different beasts - both call instance methods.

invokevirtual will invoke an instance method, with dispatch based on the class of the object reference. If a method can't be found an AbstractMethodError is raised.

invokespecial contains special handling for:
  1. superclass method invocations (actually checks the resolved method's class is a superclass of the current class)
  2. private method invocation
  3. instance initialization invocations ( methods, which are void functions generated from constructors)

Monday, 4 August 2008

Who are the top Java / SUN bloggers?

Rich Green, head (& Executive VP) of software at SUN:
http://blogs.sun.com/richgreen/
Rich Green is a long-standing guy at SUN, having been a general manager of Solaris products. He was at SUN for 14 years before moving to Bill Coleman's Cassatt Corporation, specialising in virtualisation technologies. (At Cassatt, Rich was EVP of Product Development). Before leaving SUN he was a key witness in the antitrust case with Microsoft, resulting in a $1.6bn settlement and 10-year collaboration agreement.

James Gosling's ("Father of Java - the language formerly known as Oak") blog :
http://blogs.sun.com/jag
James got his PhD from CMU in 1983. He did the original design for the Java programming language and wrote its first compiler and VM. He is also the author of emacs.

Jonathan Schwartz, SUN's CEO, talks about various things including acquisition of MySQL AB:
http://blogs.sun.com/jonathan/entry/winds_of_change_are_blowing
Jonathan has a consulting background from McKinsey and replaced the previous CEO Scott McNealy who was also a co-founder in 1982, along with Vinod Khosla (now running "venture assistance" firm, Khosla Ventures), Bill Joy (author of Berkeley UNIX) and Andreas ("Andy") von Bechtolsheim (UNIX workstation innovator). Vauaghan Pratt, a Stanford University professor, advised the company.

Mike Dillon, SUN's General Counsel:
http://blogs.sun.com/dillon/
JD from University of Santa Clara, has worked for a number of law firms in the Bay Area.

Michelle Dennedy, SUN's CPO:
http://blogs.sun.com/suncpo/
Has both a legal and science background.

Sunday, 3 August 2008

What's an iterator and what are the rules of thumb?

Some collection classes can be traversed via a java.util.Iterator interface. It is not generally advisable to modify a collection when traversing it via an iterator.

Wednesday, 30 July 2008

How EXACTLY does garbage collection work in Java?

gc -

main purpose: freeing memory from objects no longer referenced by the program

what does no longer referenced mean?

refcount==0

when is refcount==0? Most profilers use JVMPI or JVMTI (only in J2SE 5.0) to obtain reference counts of objects. MPI == machine profiler interface, MTI == machine tool interface (referring to the Java virtual machine of course).

secondary purpose: combat heap fragmentation (blocks of heap memory in-between blocks of live objects)

designer of each JVM must decide how to implement the gc-collected heap.

benefits:
1. productivity
2. security - prevent programmers from accidentally (or purposely) crashing the JVM by incorrectly freeing memory

What is object equality in Java?

The Object class in Java has two methods that refer to equality: equals() and hashcode(). In general, if you override one of these methods, you must override both, as there are important relationships between the two.

Specifically? If two objects are equal according to equals() they must have the same hashcode() value (reverse not necessarily true).

if o1.equals(o2) then hashcode(o1) == hashcode(o2)

The default implementation of equals() provided by Object is reference equality:

public boolean equals(Object obj) {
return (this==obj);
}

This is a neater way of saying if(this==object) return true; return false;.

By this definition, 2 refs are equal only if they refer to the exact same object.

Friday, 25 July 2008

Getting to know java.lang.Object

This is the fundamental class in Java, every Java programmer ought to know it backwards! The Object class has concepts of multithreading, hashing, copy construction and RTTI embedded into it.

An example of RTTI built into the Object class is the getClass method, which returns the runtime class of an object. An example of the copy construction concept built into Object is the clone method.

What does finalize() do in Java?

Every class inherits finalize from java.lang.Object. The method is called by the garbage collector when it determines no more references to the object exist. Should normally be overriden to clean up non-Java resources e.g. closing a file. Good idea to free resources in a try-catch-finally and then call super.finalize(). Finalization is never run more than once on any object. It's generally best to clean resources in a try-catch-finally rather than in finalize() to ensure timely cleanup.

Important note: when an application exits, the JVM will NOT execute finalizers of any object left on the heap. To change this behaviour you need to call the method runFinalizersOnExit, this method is deprecated however as it can result in deadlock.

Objects can be resurrected using finalizers in Java. finalize() is called as an object has no more references. But suppose finalize then adds the object to a static "live" linked list. The object now has an additional reference and can't be garbage collected.

How is a class represented in the JVM?

What happens when I run a Java program?

LLII of the Valley

What happens when you start a Java program can be summarised in four steps (LLII). Loading, Linking, Initialization, Invoke Main. (Ch5 JVM spec covers this in detail).

  1. The bootstrap class loader loads the initial class.
  2. JVM links the class, initializes the class and invokes the main method.

What does loading involve?

Loading involves locating the binary form of a class or interface type (usually the class file format, and constructing a Class object to represent the class or interface). 

The loading process is defined by the class ClassLoader and its subclasses. If an error occurs at the loading stage, a LinkageError will be thrown. An example LinkageError would be a NoClassDefFoundError.

What does linking involving?

"Linking a class or interface involves verifying and preparing that class or interface, its direct superclass, its direct superinterfaces, and its element type (if it is an array type)" (JVMSpec)

Verifying a class means ensuring its binary representation is structurally valid. A VerifyError is thrown if structural constraints on JVM code are violated.  Preparing a class means intialising the static fields to their default values. This does not result in execution of any Java machine code.

What does intializing involve?

Initializing involves init'ing static fields in the class, and any static initializers (procedural code  declared in a static {} scope). There may be other methods that need initialising for example to support Reflection API.

What does executing main involve?

Running the linked program!

Essential reading for Java Programmers




Blog Archive