Saturday, July 28, 2007

Never Multi-Thread Your System Clock 3

A FAIR ENOUGH IMPLEMENTAION.

Am sure you did read the first blog on this topic? Let me remind you a point from it: any number of men can pass through a door which is supposed to allow only one man at any time if they can all piggyback into the door, provided the height of the door is sufficient to take as much piggybackers.
I can implement piggybacking for this time zone problem by creating three separate threads for each time zone, such that the first thread calls the second and the second calls the third. You can create any number of time zone references this mind. Like the Mahjong game, you can even create four. But caution! Sshhh... read to the end first. This thread calling is best done with ThreadGroups. A ThreadGroup makes it possible that where one thread gets interrupted or a parent thread gets interrupted, all the threads die together.
Now for the code. For a challenge, write a third thread that is declared in the second thread or the Hawaii standard time thread in the code below.




import java.lang.*;
import java.util.*;
import java.text.*;

public class FairEnough implements Runnable {
String dZone = "Local";
//every thread exists in a group such that
//they all die together
ThreadGroup dGroup = new ThreadGroup("myGroup");
//the time zones am going to use, simp for UTC and
//zHst for Hawaii Standard Time.
SimpleTimeZone simp = null;
SimpleTimeZone zHst = null;
//computing this long now prevents future recursive
//computing
long oneHour = 1000*60*60;

/** Creates a new instance of FairEnough */
public FairEnough(String zoner) {
//if string is utc, run utc else if hst run hst
if (zoner == "UTC"){
this.dZone = zoner;
//set the time zone to utc
simp = new SimpleTimeZone((int)oneHour*0, dZone);
//create the utc thread in a a thread group and start it
Thread utc = new Thread(dGroup, this);
//start our thread
utc.start();
//utc object now calls the hst object
FairEnough second = new FairEnough("HST");
}else{
//this here is constructor code for hst object
this.dZone = "HST";
zHst = new SimpleTimeZone((int)oneHour*10, dZone);
//create hst thread
Thread hst = new Thread(dGroup, this);
hst.start();
}
}

//the run method defines the thread itself.
public void run() {
//LIMIT means i don't want this thread to run for
//more than five minutes
long LIMIT = 1000*60*5;
//this is the guard on five minutes limit
long timeSpent = 0;
//this is the guard on timer, reference to the
//instance in time when run started, +/- nanoseconds
Date dater = new Date();
//our thread could be interrupted, so let's put
//it in a try
try{
while(timeSpent < LIMIT ){
//create date formatter formatting only time
DateFormat formatter = DateFormat.getTimeInstance();
//specify time zone to use
if(this.dZone == "UTC"){
formatter.setTimeZone(simp);
}else if(this.dZone == "HST"){
formatter.setTimeZone(zHst);
}
//print out our time
System.out.println(this.dZone +" time is "+formatter.format(new Date()));
//sleep 3 seconds
Thread.sleep(1000*3);
//update system time
Date now = new Date();
//compute the time spent doing this stuff
timeSpent = now.getTime() - dater.getTime();
}
}
catch(Exception e){
e.printStackTrace();
}
}

public static void main(String[] args){
//specify time zone to start with. if utc or hst.
//use upper case please!!Mine!!
FairEnough fair = new FairEnough("UTC");
}
}

Caution: I ran the code above on a 1.2 Ghz Pentium III Intel and was my puter humming all the time. Not to worry, he's just complaining to deaf ears. That goes to show you that this is not a very good candidate for implementing this concept, just a solution just made it. If you're really that bold, try getting driver magic if you're experimenting with clocks and threads first.
In my magic bag is a simple, affordable solution that you'll make use of and your puter wouldn't realise you came into its machine space. Ready for the last and final blog on this topic? I sure am.

Never Multi-thread Your System Clock 2

HOW NOT TO GO ABOUT IT.

A little on threading. A thread is like a process that is running inside another process. Imagine the wheels of your car running when the car starts. But never imagine the beautiful baby on the left could ever be yours. Now, in Java programming, when a thread wants to access or reference a variable, it has to acquire the lock on the object or variable, which we'll refer to here as its monitor. And no two threads can acquire the same lock on a monitor. Rather, if a thread wants the lock on a monitor and another thread has it, it has to wait for that owner thread to release the lock first.






I love small cars

Our clock has to be in three time zones, one in the New Zealand Standard time, another in Universal Time and the other in Hawaii Standard Time. It looks simple to just create separate threads, taking from our example in the first blog for this title. No, creating three threads for the three time zones will not necessarily run. There are issues to consider.

Issue of monitor locking. If we have say three threads, thread A, B and C and A starts executing first. Other threads have to wait for it but they have already been called to start. There is no way we should expect B and C to return the same time as A. Clocking is dynamic and time never waits for any man. The error reporting chain gets propagated indefinitely as B gets the baton and as C acquires a subsequent lock.



Fighting with your throat? It stops right here.

Issue of thread sleeping. It would seem some solution to ask A to sleep and pass the baton to B and then to C and then to receive the baton or lock later. That was what we would all assume the normal should be. But this is no solution at all because if thread A enters a sleep state, are we sure it will ever recover from one? Will it not sleep forever? Let's say, A starts sleeping, to sleep for 1 second. B begins to run and then enters a sleep that lasts for also one second. Are we not to assume that A and B will ask for the lock at the same instance? Even if they have to sleep for any second at all! Both threads will have to eventually fight for the lock. We are setting the stage for a fight on the system time or our monitor. If B wins, A ends up fighting with C. Will A win? As in life and in threading, no thread can fight for long. One would give up and throw an interrupted exception and stop executing. So, why not put a usage clause on our thread. Imagine that! We'd rather never have to implement a thread in the first place.

But we'll never give up here. There's a solution for our threading problem. I found on the bottle to your right a natural solution to a throat problem, and it's the New Zealand way. That was while googling on New Zealand. In a new way, I'll demonstrate two ways this problem can be solved.

Thursday, July 26, 2007

NEVER MULTI-THREAD YOUR SYSTEM CLOCK

THE BREEZE SECTION.


If three men have to pass through a door that can take only one, how many men can pass through at any one time?

“Hey, you? ”

“One.”


“Why one?”

That's the question, why only one? Can't they piggyback through the door, like the one in front having another on his back and another on his back and another ad infinitum, provided the height of the door can accommodate as many? Well, convention and dynamism are two ends of the same stick. The longer one stays it becomes the other.


Now before we enter the door of seriosity, I'll like to unwind with a cup of Chinese tea. I like the ginseng blend. Which do you prefer? Choose yours.


I had this question thrown to me recently: How can one implement three threads such that they reference the same time while preventing deadlock and other issues known with threads.

What would you answer? As they always say, KISS. Keep it simple, stupid. So I decided to write a simple class that displays just one time, just one thread, my system time converted to UTC time. Foremost on my mind was what the thread was going to do: simple, just update my system time, convert it to Universal Time and format it in a simple human-readable format.





import java.text.DateFormat;
import java.util.*;
import java.lang.*;

public class Availables implements Runnable {

DateFormat firstFormatter;

public void run() {
//get my present instance
Date date = new Date();
//an a simple utc time zone converter
SimpleTimeZone utcZone = new SimpleTimeZone(0, "UTC");
//i don't want this timer to run just five minutes
final long LIMIT = 1000*60*5;
//then i'll set a time guard on our time
long timeSpent = 0;
//while the thread is running, i expect to receive an
//interrupted exception. maybe from my puter
try{
//what next? until five minutes runs out
while(timeSpent < LIMIT){
//set the time zone for our time
firstFormatter = DateFormat.getTimeInstance();
firstFormatter.setTimeZone(utcZone);
//print out what the present time is
System.out.println(firstFormatter.format(new Date()));
//ask the thread to sleep for 3s seconds, to
//simulate a real timer
Thread.sleep(1000*3);
//update our thread, compute the elapsed time
Date now = new Date();
timeSpent = now.getTime()- date.getTime();
}
}
catch(InterruptedException e){
e.printStackTrace();
}
//little checker. unecessary, but you never can tell
if (Thread.interrupted()){System.out.println("Finished.");}
}

public static void main(String[] args){
Availables newbie = new Availables();
Thread tre = new Thread(newbie);
tre.start();
}
}



Now, how about the other threads that had to show different time zones, say Hawaii standard time or New Zealand Standard Time? And to talk of Hawaii, if you had to choose between a special Home in Florida and a week in Hawaii, which would it be. I saw this lovely house, and my, did i fall in love with it. Would you still go to Hawaii?

Monday, July 23, 2007

DOES A PICTURE SAY A THOUSAND WORDS 3?

I won't bore you any longer with steps to take, you already know them. After the First and Second blog on this topic, this here is the last and am sure you'll appreciate coming here. The javax.imageio package provides a custom decoder (what I thought the CharsetDecoder class would do for me!) through the ImageIO class.

This here is the code. Before Coding, have you played some high performance games lately?





package examples;

import javax.imageio.*;
import java.awt.image.*;
import java.io.*;

public class Byter {

BufferedImage buffer;
File f;

protected void doThis(){
try{
//grab the file in a file reference, handle exception also
f = new File("amelipassport.jpg");
//use a static method read of ImageIO to buffer file
buffer = ImageIO.read(f);
//test buffer. You'll get two results, the ColorModel and Raster
//try and see
System.out.println(buffer.toString());
}
catch(IOException e){
e.printStackTrace();
System.err.println("File not found");
}
finally{
//finally call the raster for character rep.
//of the pixels in each cell. int returned by getRGB is 8 bits
for (int i=0; i<314;i++){
for(int j=0; j<274; j++){
System.out.print(buffer.getRGB(j,i)+",");
}
System.out.println();
}
}
}

public static void main(String[] args){
Byter by = new Byter();
by.doThis();
}

}

little challenge: send the output of Sysout to a “.txt” file and you'll see the table arrangement of the character representation of the colors you saw in the picture above.

A picture doesn't say a thousand words, you'll never understand them unless you know the language it was speaking in.

When the code ran, what I read from the output was that the picture has two components, a ColorModel and a Raster of image data. The results i got for the young beautiful dark african in the picture above is: This image is one of 8 bits in RGB colors, in windows style BGR color model with Red, Green and Blue of 3 bytes. There is no alpha value in the picture because this is false. The picture is set to 100% transparency and has a width of 274 pixels with a height of 314 pixels.
Try your hands on any picture of your choice and try reading what was said.

But for sure, appreciate colors, appreciate beauty and appreciate the picture even if the language seems difficult for you to understand.



DOES A PICTURE SAY A THOUSAND WORDS 2?

Faced with the task of decoding that picture of a young african girl, I said to myself, small fry. It'll be handled in a breeze. After I finished writing the first blog of this series, I went outside to the fresh air, drank some water and popped some gums into my mouth. How long should this take me? An hour, two, or three at most. Trust me, this is work just for a Gothamite.

First course of action : I'd grab the image files through a Bufferedinputstream, decode the files using the default charset decoder and maybe a decoder also of the utf-8 charset and then write the decoded data out through a BufferedWriter. That should do it. I'd get a character representation of the image data. So, I set out coding and this is what i wrote.


Standards are what we'll be living by in our codes, like engineering standards, Web standards...etc





package examples;

import java.io.*;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;

public class Tunes {

CharBuffer charBuf;
ByteBuffer byteBuf;
BufferedInputStream bin = null;
//writer wasn't called. i used Sysout to look ahead.
BufferedWriter bufWriter;
String strChar;
//default character set for my machine is windows-1252.
//tried default and also utf-8
Charset cs = Charset.defaultCharset();
byte[] toUse;
public void doFinal() throws FileNotFoundException,IOException {
try{
//create a buffered file inputstream
bin = new BufferedInputStream(new FileInputStream("amelipassport.jpg"));
//we want to use the default character encoding
//and the default byte buffer size
//we'll use a file writer on a file output stream'
bufWriter = new BufferedWriter (new FileWriter("writeout.txt"));
int c; // check on int returned by file read
//provided there are data in the file,
//keep reading your file and writing to output until
//you get to end of file
toUse = new byte[bin.available()];
while ((c =bin.read(toUse)) != -1){
byteBuf = ByteBuffer.wrap(toUse); //i have a byte buffer now
charBuf = byteBuf.asCharBuffer();
}
}
finally{
//call the charset decoder reset method
Tunes newTunes = new Tunes();
//i used a helper class, HelpDecode
Tunes.HelpDecode helpDecode = newTunes.new HelpDecode();
//follow api instructions to letter. first reset(), decode(),
//final decode(), then flush()
helpDecode.reset();
CoderResult coder = helpDecode.decode(byteBuf, charBuf,true);
//never used the buffer writer since i had to lookahead on
//what my machine was supposed to do
//decode returned malformed
//input byte sequence not legal for this character set,
//even on utf-8
System.out.println(coder.toString());
coder = helpDecode.flush(charBuf);
System.out.println(coder.toString());
System.out.println(charBuf.toString());
//close all your two streams if any is still open
if (bin != null) {bin.close();}
}
}

//helper class HelpDecode extends CharsetDecoder
private class HelpDecode extends CharsetDecoder{
protected HelpDecode(){
//let max and avg charsperbyte be similar
super(cs, 255.0f, 255.0f);
}

protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
//used underflow as a check on result
return CoderResult.UNDERFLOW;
}

}
public static void main(String[] args)
throws FileNotFoundException, IOException {
Tunes nTunes = new Tunes();
nTunes.doFinal();
}
}

From the code above you should realise that I can't decode the image file that way. It's not possible. I took a step from the code and asked myself: “what erroneous presumptions do I have about decoding this file?”

One, the “.jpg” file can be referenced by a File object.
Two, image files should be binary data.

The decoding process just can't do what I want it to do and by the way, my decoder class that was supposed to inherit from CharsetDecoder doesn't inherit any method that reads bytes and decodes them straight to char values, just as I expected.

Bad day. There goes my lunch. There must be a way.

Yes there is. I found one late at night. The java.awt.image package and the javax.imageio packages have just what I wanted. They can even decode images. Great. I had to write the third and definitive piece just for you.



Friday, July 20, 2007

DOES A PICTURE REALLY SAY A THOUSAND WORDS?

I took a look at a picture, a picture of a young beautiful dark african lady on my laptop and decided, what if i see how the computer translates this simple picture into text. What would the computer say about this lady? I had to go about it.


I delved into the Java API and was told, just read the image binary file, buffer the input stream and then write it out in another buffered output stream. Pronto. I checked the java tutorials and was told the same story. Just do that and you'll be fine. So i tried it and am giving you the result.
If you love chinese games, you really might be interested in Mahjong. There is also one for PocketPCs.




package examples;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.*;

public class Google {
BufferedInputStream bin;
BufferedOutputStream bout;

public void doingThis() throws FileNotFoundException, IOException{
try{
//create the input stream
bin = new BufferedInputStream(new
FileInputStream("amelipassport.jpg"));
//create the output stream
bout = new BufferedOutputStream(new
FileOutputStream("pix2words.txt"));
//now there's this int type that i'll use to read the
//bytes coming from the buffered input stream
int c;
//we'll keep reading the stream and writing to output
//until we each end of file, eof
while((c = bin.read()) != -1){
bout.write(c);
}

}
finally{
//at the end of everything, close all streams
if (bin != null){ bin.close();}
if (bout != null) {bout.close();}
}
}

//now this is the class loader
public static void main(String[] args) throws FileNotFoundException, IOException{
Google blogger = new Google();
blogger.doingThis();
}

}

I had the honor of asking the unholy question: What would the computer say? Now these are a few lines of my result.


ÿØÿþ WANG2ÿà JFIF  x x  ÿÛ C  
(1#%(:3=<9387@H\N@DWE78PmQW_bghg>Mqypdx\egcÿÛ C//cB8BccccccccccccccccccccccccccccccccccccccccccccccccccÿÀ :! ÿÄ    ÿÄ µ  } !1AQa"q2‘¡#B±ÁRÑð$3br‚
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡&circ
;‰Š’“”•–—˜™š¢£
¤¥¦§¨©ª²³´µ¶·¸
¹ºÂÃÄÅÆÇÈÉÊÒÓ
ÔÕÖרÙÚáâ&atild

I really don't know what the computer said. I can see WANG2 and then after...Gibber-gibber-gabber-dash? Or something like that?There must be a way to understand this gibber language. Yes, there is, i have to decode the gibberish stuff. Going back to ask the API.“Hey, API, you told me some half truth. Now, wise man, how do i translate this gibber?”

I've already written a solution. It's a breeze away.

And for those who cannot do without being mobile, here's something you might like, Mundu for Mobiles.


Tuesday, July 17, 2007

EXPLORING TWO BOOLEAN OPERATORS

Two operators that are quite similar in functionality but for which a developer has to be conscious of bugs creeping into his code are the boolean logical inclusive or, | and conditional-or, ||, operators.

The operands for both operators should be of type boolean or the boolean wrapper, Boolean. One difference between both of them is that the conditional-or || operator evaluates its operands differently and in a subtle fashion than its counterpart, the boolean logical inclusive-or | operator.

Let's illustrate this with a truth table.


































table illustrating both boolean operators
T F Result: Logical inclusive-or | operator Result: conditional-or operator ||
T T T T. Ignores right operand and proceeds to next expression.
T F T T. ignores right operand; proceeds to next expression
F T T T. evaluates right operand which is true where left operand if false and proceeds to next expression.
F F F F. evaluates right operand which is false where left operand is false. Proceeds to next expression.


This is the difference between both operators: although they give the same result for truth or falsity, operand evaluation is different. From the table, realize that where the left operand is false for a conditional-or operand, the right operand is then evaluated, else where the left operand is true, the right operand is ignored.

So what's the consequence of this effect?

Let's take a simple question: which of the options below is not robust enough to throw a null pointer exception?


Option A: if ( (myArray != null) | (num == myArray.length()) );
Option B: if ( (myArray != null) || (num == myArray.length()) );
Option C: if ( (myArray == null) | (num == myArray.length()) );
Option D: if ( (myArray == null) || (num == myArray.length()) );

Answers:

Option A: if left operand is true and right operand is true or false, the if-statement evaluates to true and the expression after the if statement is next evaluated. If left operand is false, the if-statement will always throw a null pointer exception.

Option B: if left operand is true, execution jumps to the expression following the if statement, else a null pointer exception is immediately thrown.

Option C: if left operand is true, a null pointer exception is immediately thrown because the right operand would never be evaluated. If left operand is false, if statement evaluates to true if the right operand is true, false otherwise.

Option D: if left operand is true, execution immediately jumps to the statement following the if-statement. If left operand is false, right operand is then evaluated. If right operand is true or false, no null pointer exception will ever be executed.

So which option will never throw a null pointer? You guessed right, option D.

Monday, July 16, 2007

Generating Random Numbers

Quest: a trivial exercise in generating random integers that one can class as either zero, even or odd between zero (inclusive) and eleven exclusive. After these integers, nine in all, are generated, classification is done and the result of the number of zeros, evens and odds in the total numbers generated is then printed to the screen.


Find: i”ll use an instance of a RandGenerator class to reach the above goal. Importing the class Random from the package, java.util, the following fields are declared by our RandGenerator class:



import java.util.*;

public class RandGenerator {
//the array to hold the numbers generated
private int[] boxArray = new int[9];
//declaring an instance of our random number class
private Random rand;
//counters for the integers generated
private int oddCount=0, evenCount=0, zeroCount=0;

we'll make use of two methods, a generator() that uses the Random class to generate nine integers from between zero (0) and ten (10) and then inserting the integers into an array.



//method that generates random numbers as int values
private void generator(){
rand = new Random();
//this for loop generates 9 consecutive random numbers
for (int i =0; i<9; i++){
//get a random number between 0 and 11 exclusive
//and store in an array of ints
boxArray[i] = rand.nextInt(11);
}
}

Another method, probing(), accesses the array for its int values, maps each int trivially to either a zero, even or odd class and increases the count for each class so mapped. Note that the mapping is assumed. Finally, this class prints out the numeric value of the numbers generated for each of zero, even or odd classes from accessing the array.



//method that evaluates the numeric count of the integers
//generated randomly according to a zero, even and odd class
private void probing(){
//starting from the first to the last element in the array find out
//what integer was generated
for (int i=0; i‹boxArray.length; i++){
int take = boxArray[i];
//if integer generated is zero, increase zero count
if (take == 0) {
zeroCount++;
}
//if even integer generated, increase even count
//by one
else if (take % 2 == 0){
evenCount++;
}
//otherwise odd integer generated, increase count
else {
oddCount++;
}
}
//print out the result of the count values
System.out.println("Number of odd values"+
"generated were "+ oddCount+" .");
System.out.println("Number of even values"+
"generated were "+evenCount+" .");
System.out.println("The zeros generated were" +
zeroCount+" in number.");
}

Finally, you can run this code by instantiating the class and just calling the two methods.



public static void main(String[] args){
RandGenerator random = new RandGenerator();
random.generator();
random.probing();
}

Thinking of another quest for next blog. Promise it'll be great