Posted in Uncategorized

Java Post #3 Java Overloaded ミ●﹏☉ミ

You want to do several things at once? 
Or stop suddenly but gracefully? 
In this post I’ll try to post about two different things: 
Threads, and Exceptions 
The concepts needed for thinking about these are introduced, since you can’t avoid dealing with these in Java, and Java’s mechanisms for dealing with them are shown.


Normally, in your program, there is a flow of control. You can tell the flow how to go by calling functions, using loops, etc. It is like there is one little bustling gnome, being told what to do as it goes from line to line of your code.
A natural idea, especially when you want your program to do two unrelated activities, is to let there be more than one gnome. Each gnome can then follow code around, line by line. Of course, you will need to take care that they aren’t each messing with variables that the other is using — that would cause a lot of confusion for the poor gnomes, and their algorithms would be ruined!
All the object-oriented metaphors talk about the “object” performing the activities described in its methods. Don’t be fooled! Gnomes do the work. For example, one object can do two things at once, if two gnomes are executing its code. If an object doesn’t have any gnomes doing work for it (and this is usually the case for most objects, since there are typically many more objects than gnomes), then it can’t do anything at all until a gnome arrives on the scene. And in fact, the gnome manipulates the object, not the other way around. The only “control” the object has over anything is that in some sense the code represents the will of the object. A method is something that the object might be asked to do. The code for the method represents how that kind of object chooses to respond to that request, and it is executed by any gnome that is sent to that method. Objects never get to do anything except respond to requests and messages. (Often the requests are actually sent from the object to itself. For example, an object that is asked to go to the next room might first ask itself to stand up, and then ask itself to walk in a certain direction.) “Being asked to do something” means that a gnome is sent to the object’s method for responding to that request. When the gnome is done handling a request, it returns to the higher-level request that it had previously been working on. The object-oriented jargon talks about a “method” being “invoked” or a “message” being sent. Really, a gnome is sent. Sometimes the gnome is sent with a message, and sometimes it is sent with a request. The only difference is in your mind. A gnome always arrives just to perform a specific method, and when it is done, it leaves. They have an incredibly strong work ethic.

Computer gnomes wear rather threadbare clothes compared to their cousins in the forest, and so the unfortunate slang term “thread” arose for these gnomes. However, their hard work has earned this term a lot of respect, and now they even call themselves “threads” with pride!
In Java, each gnome (each thread) has a Thread object associated with it. This object stores the name of the thread, along with any other knick-knacks a thread might desire. The thread itself is just running around mindlessly executing code, and has no memory or sense of self. Actually, that’s not quite true. It has its own call stack, where it keeps passed arguments, local variables, and return values. And it knows where its Thread object is. That is where it stores its name and so on. This can come in handy for example if you have different instructions for different threads (you would have instructions like “if your name is Sam, do such and such”).
Thread.currentThread() is an introspective class method — if you send a gnome off to execute this method, then it will come back with its associated Thread object.
new Thread(name) creates a new soulless instance of the Thread class, a “missing gnome” file. 
If a gnome X executes the start() method for a “missing gnome” object, then the “missing gnome” comes into being as a real live gnome Y, and Y runs off to execute its run() method. The original gnome X just returns to its caller, without worrying about what the new gnome is up to. If the new gnome Y ever returns from the run() method, it is automatically and painlessly terminated.
When Y comes into being, it looks for its run() method. It may have one itself, if it is a subclass of Thread that has a run() method. But it might not have one — then it looks for a run() method of its “target” object. What is its target? 
new Thread(obj,name) makes a new instance of the Thread class, which has obj as its “target”. The class of obj should implement Runnable (have a run() method).
There are various methods of the Thread object that control the activity of the associated gnome: 
(I think they all also exist as class methods, operating on the gnome that executes them.)
The stop() method immediately and painlessly terminates the gnome (by throwing a ThreadDeath error exception at it!). If the gnome had not yet been created (i.e. it was a “missing gnome”), it doesn’t matter — it is quite dead after this, and has no chance at life. This is an asynchronous death, so for gnomes that could leave things in a disordered state, it is better to set some flag that they can check at a safe time, killing themselves if they find it set.
  • The sleep() method causes the gnome to immediately fall asleep for the specified number of milliseconds. When it wakes up, it will continue where it left off.
  • The suspend() method puts it to sleep until someone else executes its resume() method.
  • If the thread calls wait(), then it sleeps until that thing calls notify() or notifyAll().
  • If a gnome is supposed to do some I/O on a device that is busy, it will fall asleep until the device is free. This is probably implemented with the above strategies.
You can setPriority(p) with Thread.MIN_PRIORITY <= p <= Thread.MAX_PRIORITY 
or setDaemon(true) (interpreter will exit when only daemon threads remain).
Sometimes there might be different gnomes that need to work with the same data. They can’t both work on the data at the same time, or terrible things could happen:
Gnome 1                          Gnome 2
————————-            ————————-
pick up the scissors
                                              pick up the scissors

                                              put fabric 2 in scissors

                                              position fabric correctly
put fabric 1 in scissors
                                              cut fabric
position fabric correctly
                                              put fabric down
cut fabric

put fabric down

Here each gnome is doing something that by itself seems sensible. But at the same time, another gnome is messing around with the same scissors, and the result is disaster! Gnome 2 is cutting the wrong fabric in the wrong place, and Gnome 1 winds up snipping thin air! This just goes to show how brainless threads are. They are so busy working that they never look up to see if what they’re doing makes any sense.
People usually solve this in the following way: Whoever gets to the scissors first gets to use them until they are done, at which point they give the scissors to the other person, who had to idly wait until they got the scissors.
From an object-oriented point of view, we might have an object theScissors, with a method cutFabric(). To solve the problem of thread brainlessness, theScissors would know that there are certain activities that are only safe for one gnome to do at a time, such as cutting fabric. Such activities (methods) are marked with the keyword “synchronized”. Any time any thread wants to start executing synchronized code, it will first make sure no one else is doing so for that object. If someone else is doing so, it has to wait its turn. But once it is executing the synchronized code, it can be sure nobody else will do so until it has finished.
The way this works is that there is a solid gold baby monitor excavated from the tomb of Cheops. This item is popular with objects, but since the real article is in the London museum, each object just has a little gold-tone plastic replica. There is a bizarre tradition dictating that gnomes may only enter “synchronized” code if they have the object’s baby monitor. Only one gnome can have the monitor at a time, so if a gnome enters synchronized code on behalf of a certain object, no other gnomes may do so until it has finished with the synchronized code, thus relinquishing the monitor.
synchronized (myObject) {code executed when myObject’s monitor is obtained}
  • wait() — sleep until notified (letting go of monitor)
  • notify(), notifyAll() — wake up all waiters.
These can only be called when you have the monitor — why???
Are constructors automatically synchronized? The docs say it can’t matter, since nothing else can see the object before the constructor finishes. That doesn’t seem right, though. ???
     try {code that might throw exceptions}
     catch (MyThrowable var1) {…}
     catch (Throwable var) {…}
     finally {…}

If an Error or Exception is thrown, then the first (if any) applicable catch is executed. In any event, the finally block is executed, even if the remainder of the function will be skipped due to an active exception..
Here’s how to indicate that your routine may emit a throwable instead of its return value:
public void writeList throws IOException, ArrayIndexOutOfBoundsException {…}
Here’s how things are thrown:
throw aThrowable;
Runtime exceptions can happen from any function — functions do not need to declare that they might throw them. 
Examples are 1/0, null.x, a[-3], etc.
There are two built-in kinds of Throwable:
Error, for bad conditions that one is not expected to recover from
(an error in the runtime system, or in a dynamically loaded class file, or a ThreadDeath)
Exception, for trip-ups that a program should be able to recover from
(mostly IO — things the code might hope won’t happen, but can’t tell in advance)
RuntimeException, for when a program goofs up
(in arithmetic, using arrays, etc. — things a careful code-examiner could have predicted)
Exceptions that are not RuntimeExceptions, therefore, are trip-ups that a program should be ready for, such as file-not-found when trying to open a file, etc.
Let’s consider the FileNotFoundException. You might think that a careful program could first check to make sure the file exists, and only open it if it exists. But even this is not 100% safe — another program could delete the file after you checked that it exists, but before you opened it. The only way to really tell whether you can open it is to just try, and see whether you succeed or fail. In Java, failure is indicated by an exception being thrown.
As such, the compiler requires that such exceptions be specified in the function declaration if they might be thrown by the function. So if you have a function that opens a file, and it doesn’t bother to catch the file-not-found exception, then the exception will be thrown to the calling function — the function declaration must specify this, so that callers know to expect the exception.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s