Diary of a Player

Well I had the pleasure of picking up a digital copy of Brad Paisley’s Diary of a Player this past weekend and it was a refreshing read for someone who alternated back and forth between reading software engineering forums, survival manuals, and intense musical theory books. For anybody who has any interest in Brad Paisley at all this book tells the heartwarming story that is Brad Paisley’s life. Good for a lazy weekend read if your interested. Check it out!
What should I read next? Garth Brooks biography or the second Hunger Games novel? Hmm. We shall see!
[Feb 14 2011] Update
Hey all,
I very much enjoy bringing you the tutorials I’ve been making an effort to write as of late. However life caught up to me as usual and I am a little swamped at the moment. For one I am finishing up a course of algorithm analysis which is hogging most of my time (or at least should be). Outside of the educational realm I’m trying to get re-integrated into the open source community. I was hoping to get involved with a Google Labs project but there is nothing that really piques my interest right now so I’ve been looking at getting involved with Mozilla again. Another thing that’s going on is a friend and I are in the process of starting our own little open source project that will remain secret for now (expect announcements in the future).
On the musical front I have a couple projects on the go also. The most active one being a project which I have been recruited as a session guitarist for. The second most active one right now would be my enrollment in a band (more to come on this later). And the third musical project is my writing project whereby I hope to create an album of just my own music for friends and family.
On top of all these things I am working about 50 hours a week right now because I’m currently in “transition” between being a chauffeur and working in development. I’ve been spending my weekends at my property logging a trail and using the wood from that process to build a corduroy road up another trail that is too wet to use in the summer. MY girlfriend and I are also going through the feasibility phase of moving to Toronto. This all depends on both of our abilities to get jobs relatively close to the core and whether we can find reasonable living accommodations whereby we’ll be happy but not burnt out of all our money to stop us from enjoying the other aspects of living in the big smoke. This is all while maintaining a 5-day-a-week workout regime and trying to be a good boyfriend and family member. Needless to say it’s been very hectic and I look forward to bringing more tutorials and fun stuff to you all soon.
Look at it this way, in the near future I’ll be bringing you all some new programming tutorials, music tracks, maybe videos, and definitely some info on the open source stuff I’m getting into. I’d like to find a way to do some guitar and music tutorials also but it’s just a matter of finding a way to do that effectively at the moment.
You’ll hear back from me soon!
What’s in the fridge?
As I hope some of you have noticed the more I write these tutorials the more I try to make them fun for us all. So today I’ve prepared a fun little web services tutorial to show off some super basic web service stuff using JAX-WS (Java API for XML – Web Services). As usual let’s not blubber on with the lead up lets get right into it!
Here’s the plan: We’re going to design and code a web service that uses a singleton to store objects. The important things the web service will be able to do is add an object to it’s collection, take an object out of the collection, and get a list of the objects in the collection.
To address this I’ve come up with the idea of using a fridge as our collection. The fridge will store a number of items that are just Strings for the purpose of this tutorial. So here is the fridge web service interface.
FridgeWSI.java:
package wssample1; import javax.jws.WebMethod; import javax.jws.WebService; @WebService public interface FridgeWSI { @WebMethod String whatsInFridge(); @WebMethod void putSomethingInFridge(Object o); @WebMethod Object takeSomethingOutOfFridge(Object o); }
Now let’s implement the FridgeWSI interface.
FridgeWS.java:
package wssample1; import javax.jws.WebService; @WebService public class FridgeWS implements FridgeWSI { private static FridgeWSI self; private static java.util.ArrayList<Object> fridge; private FridgeWS() { fridge = new java.util.ArrayList<Object>(); } public static FridgeWSI getInstance() { if(self == null) { self = new FridgeWS(); } return self; } @Override public String whatsInFridge() { String ret = ""; if(!fridge.isEmpty()) { for(Object o: fridge) { ret += o.toString() + ", "; } } else { ret = "nothing"; } return ret; } @Override public void putSomethingInFridge(Object o) { fridge.add(o); } @Override public Object takeSomethingOutOfFridge(Object o) { Object ret = null; if(fridge.indexOf(o) > -1) { ret = fridge.get(fridge.indexOf(o)); fridge.remove(o); } return ret; } }
So what do we do now that we have our web service functionality coded and ready to use? Well since it is a “web service” we’ll need to host it somehow. For the purpose of this tutorial we’re just going to do it locally with GlassFish on localhost:8080. You will set where you want this beast deployed in a main method. Once you run this main method it will keep running until you kill the process. So be mindful of this as you go through the next couple steps.
Note: Our FridgeWS is a Singleton meaning only one will ever exist as long as the following main process is running.
Main.java:
package wssample1; import javax.xml.ws.Endpoint; public class Main { public static void main(String[] args) { Endpoint.publish("http://localhost:8080/WS/FridgeWS", FridgeWS.getInstance()); } }
Run this naow! We’ll need the WSDL (Web Services Description Language – Just an XML file that describes your web service) to be available for the next step. Before we get into the implementation of the consumer we’ll need to get the necessary stubs from our web service’s WSDL. There are a couple ways to go about this depending on the IDE you are using. You can do it the old school way using the wsimport command in your command line utility or you can use whatever facility your IDE has made available to you to make this process easier. Execute the following command in your project source directory to use wsimport:
wsimport -s . http://localhost:8080/WS/FridgeWS?wsdl
What this does is grab some method symbols and other fun stuff which allows the compiler (and your IDE) to understand what’s going on between your consumer code and the web service.
Moving on we need to consume our web service now. I’ve done this by writing a bridge class that will be my entry point, on the consumer side, to accessing the FridgeWS web service.
FridgeBridge.java:
package wsconsumerator; public class FridgeBridge { private static FridgeBridge self; private FridgeBridge() { } public static FridgeBridge getInstance() { if(self == null) { self = new FridgeBridge(); } return self; } public String whatsInFridge() { wssample1.FridgeWSService service = new wssample1.FridgeWSService(); wssample1.FridgeWS port = service.getFridgeWSPort(); return port.whatsInFridge(); } public void putSomethingInFridge(java.lang.Object arg0) { wssample1.FridgeWSService service = new wssample1.FridgeWSService(); wssample1.FridgeWS port = service.getFridgeWSPort(); port.putSomethingInFridge(arg0); } public Object takeSomethingOutOfFridge(java.lang.Object arg0) { wssample1.FridgeWSService service = new wssample1.FridgeWSService(); wssample1.FridgeWS port = service.getFridgeWSPort(); return port.takeSomethingOutOfFridge(arg0); } }
As you can see accessing your web service is pretty simple now. We create an instance on the FrisgeWSService then we use that instance to get an instance of a FridgeWSPort. Using our instance of the FridgeWSPort we can call on our web methods.
Now finally after all of this coding we can try using our web service! Yay! I know it’s been a long wait but it will soon be worth it. The first thing we’re going to do is create a process that puts a bunch of items in the fridge for us. So let’s do that.
FridgePacker.java:
package wsconsumerator; public class FridgePacker { public static void main(String[] args) { System.out.println("What's in the fridge? " + FridgeBridge.getInstance().whatsInFridge()); System.out.println("Put a bazooka in the fridge."); FridgeBridge.getInstance().putSomethingInFridge("Bazooka"); System.out.println("Put a cat in the fridge."); FridgeBridge.getInstance().putSomethingInFridge("Cat"); System.out.println("Put a bandana ooka in the fridge."); FridgeBridge.getInstance().putSomethingInFridge("Bandana"); System.out.println("Put black face paint in the fridge."); FridgeBridge.getInstance().putSomethingInFridge("Black face paint"); } }
The output:
What's in the fridge? nothing Put a bazooka in the fridge. Put a cat in the fridge. Put a bandana ooka in the fridge. Put black face paint in the fridge.
And now we can use a separate process (just to show that you can) to look in the fridge and see what’s there.
FridgeChecker.java:
package wsconsumerator; public class FridgeChecker { public static void main(String[] args) { System.out.print("What's in the fridge? "); if(FridgeBridge.getInstance().whatsInFridge().equals("Bazooka, Cat, Bandana, Black face paint, ")) { System.out.print("COMMANDO KITTEH!"); } else { System.out.print(FridgeBridge.getInstance().whatsInFridge()); } } }
And finally the output from our FridgeChecker:
What's in the fridge? COMMANDO KITTEH!
So we’ve not only successfully created a fridge web service that has persistence and behaves as a singleton, but we’ve successfully turned an ordinary household cat into a commando. But wait! That’s not all! We’ve also created one awesome magic fridge!
Well actually we just did the fridge and web service thing successfully and the commando cat and the magic fridge are actually just kind of a fun unit test I put in our FridgeChecker code. But it was fun! It was fun? Wasn’t it?
Anyways so now you have a very basic grasp on how to make a web service.
Go tinker!
Java 1.5.0 – Varargs
Here something interesting I just discovered in the 1.5.0 release of Java: varargs. Basically the ability send a variable number of arguments to a method. No longer must we define our methods to accept arrays!
Here’s a quick sample I put together to demonstrate the concept:
Main.java:
public class Main { public static void main(String[] args) { System.out.println("countArgs(5, 1, 2, 3, 4, 5) -" + (countArgs(5, 1, 2, 3, 4, 5) ? "passed" : "failed")); } public static boolean countArgs(int numArgs, Object... args) { int numCounted = 0; for(Object o: args) { ++numCounted; } return numCounted == numArgs; } }
Above is our main method which makes a call to a method countArgs() which accepts a variable number of Object type arguments. The countArgs() method then counts the number of arguments received and compares them against the first argument which is a number we sent to the method to tell it how many arguments we sent. The output is as follows:
countArgs(5, 1, 2, 3, 4, 5) -passed
You’ll notice that varargs are denoted by the following syntax:
Object... varName
Now go, be free, make use of this awesome new language feature!
Also, if you want more information on Java 1.5.0 features head over to the Oracle J2SE 1.5.0 New Features and Enhancements Site.
I concur — concurrency craves a curator
Over the past day or so I’ve been doing some tinkering with multi-threading. I created a situation where there is a static list of integers that I want a group of threads to eat away at together. The problem is that I want each integer eating thread to eat only its fair share of the available ints.
I started with my StaticListContainer class which is the static class holding my list of integers. It provides all the required methods to be a singleton and two additional methods related to the necessary operations for the integer eaters to eat the numbers: a pop() method which returns the current int and a isEmpty() method which returns whether the list is empty or not. Here is the StaticListContainer class.
StaticListContainer.java:
public class StaticListContainer { private static StaticListContainer self; private static int[] list; private static volatile int pos; /* * Private constructor that creates a list of 10000 integers. */ private StaticListContainer() { list = new int[10000]; for(int i = 0; i < 10000; i++) { list[i] = i; } /* * Since the array is 0-indexed we need to subtract 1 from the array.length data member. */ pos = list.length - 1; } /* * Returns an instance of the StaticListContainer. If the StaticListContainer * has not yet been initialized then this method initializes it. */ public static StaticListContainer getInstance() { if(self == null) { self = new StaticListContainer(); } return self; } /* * Returns the current integer and decrements the current position by 1. */ public synchronized int pop() { int ret = list[pos]; pos -= 1; return ret; } /* * Returns true if the current position is below 0, signifying the list is empty, * otherwise returns false. */ public synchronized boolean isEmpty() { return pos < 0; } }
Here is the IntEater thread.
IntEater.java:
public class IntEater extends Thread implements Runnable { private String threadName = ""; private int fullness = 0; public IntEater(String threadName) { this.threadName = threadName; } @Override public void run() { do { // Pop the next integer and eat it this.eatInt(StaticListContainer.getInstance().pop()); fullness++; } while (!StaticListContainer.getInstance().isEmpty()); // Once all the numbers have been eaten -- display how full each thread is double fullperc = (fullness / 2500.0) * 100.0; System.out.println(threadName + " is " + fullperc + "% full after eating " + fullness + " ints."); } private void eatInt(int x) { System.out.println(threadName + " is eating " + x); } }
For brevity sake I’m only going to put the summary of fullness and items eaten from the end of the ouput here:
Charlie is 119.83999999999999% full after eating 2996 ints. Catehrine is eating 1372 Catehrine is 14.799999999999999% full after eating 370 ints. Oswald is eating 234 Oswald is 213.0% full after eating 5325 ints. Bingo is eating 1284 Bingo is 52.35999999999999% full after eating 1309 ints.
First thing that is noticeable about this output is that things are kind of wild and out of control. This is very reflective of nature as it is survival of the fittest; whoever eats the most survives and has no regard for the other IntEater’s around them. The second thing I notice here is that Catherine starved to death, Charlie is full, Bingo is still hungry, and Oswald is a glutton.
This group of IntEaters need to be controlled somehow. We need to control whose turn it is to eat the next int. In order to control this I created a class called a ThreadPool (I know EaterMediator would have been a way cooler name but I guess I was a little lame than I am now when I wrote this code). What ThreadPool does is keeps track of a group of threads and iterates through them cyclically using a next() method. It also provides a helper method called yielding() which forces a thread to yield if it is not that threads turn. If used correctly all threads will yield until the threads whose turn it is executes and calls the next() method.
ThreadPool.java:
public class ThreadPool { private static ThreadPool self; private static java.util.ArrayList threads; private int current; /* * Private constructor initializes the threads list. */ private ThreadPool() { threads = new java.util.ArrayList (); } /* * Singleton getInstance() method. */ public static ThreadPool getInstance() { if(self == null) { self = new ThreadPool(); } return self; } /* * Tell the ThreadPool that the next thread may use the processor now. */ public void next() { if(current == threads.size() - 1) { current = 0; } else { current += 1; } } /* * Add a thread to the pool. */ public void addThread(Thread thread) { threads.add(thread); } /* * Start all the threads in this pool. */ public void startThreads() { for(Thread t: threads) { t.start(); } } /* * Force a thread to yield if it is not their turn to use the processor. */ boolean yielding(Thread t) { boolean ret = false; if(threads.indexOf(t) != current) { t.yield(); ret = true; } return ret; } }
Making use of the ThreadPool our IntEater class should change to reflect the following:
IntEater.java:
... public void run() { do { // If the current thread is not supposed to be yielding then do the work if(!ThreadPool.getInstance().yielding(this)) { //Pop the next integer and eat it this.eatInt(StaticListContainer.getInstance().pop()); fullness++; /* Must call this method to tell the ThreadPool that it is the next * threads turn to do it's work. */ ThreadPool.getInstance().next(); } } while (!StaticListContainer.getInstance().isEmpty()); ...
After the changes our output summary is as follows:
Charlie is 100.0% full after eating 2500 ints. Catehrine is 100.0% full after eating 2500 ints. Bingo is 100.0% full after eating 2500 ints. Oswald is 100.0% full after eating 2500 ints.
Which indicates that each IntEater ate sufficiently what they required to be full and shared the list on ints equally.
Our main method looked like this the whole time because I was always using the ThreadPool but not using the flow control it provided for the first part of this tutorial. So now I permit you to finally read the main code.
Main.java:
public class Main { public static void main(String[] args) { StaticListContainer.getInstance(); ThreadPool.getInstance(); ThreadPool.getInstance().addThread(new IntEater("Charlie")); ThreadPool.getInstance().addThread(new IntEater("Catehrine")); ThreadPool.getInstance().addThread(new IntEater("Oswald")); ThreadPool.getInstance().addThread(new IntEater("Bingo")); ThreadPool.getInstance().startThreads(); } }
What’s next? Hmm I would be interested to see about extending the ThreadPool class to be a Thread itself which could then be used by itself to be a ThreadPool within a ThreadPool. By doing that we could make sure ThreadPools take turns using the processor equally. There would have to be a number of changes but it’s not unimaginable.
I hope this helps to bring to light some of the issues surrounding concurrency. I have a analogy for how the JVM controls multi-threading which I find helpful: picture a lineup of people waiting to read a piece of paper inside a key-locked safe. A key drops from the sky and the first person to grab it opens the safe and reads the paper. That person then closes the safe and throws the key in the air above the crowd. Everybody jumps to try and grab the key and only the person who does can access the safe. The person who catches the key might even be the same person who threw it. There is no control over the process. Now in relation to threading. Each person in the crowd is a thread waiting to access a synchronized resource. The safe is the synchronized resource and the key is the window/semaphore. Multi-threading is a pretty chaotic process which sometimes needs to be tightly controlled depending on your application. What I’ve done above is give you one such way to control it.
Don’t forget: 5 to 10 ints and vegetables a day!


