Back to another Java example, until this whole multithreading thing is understood properly, I looked at the dumbass book again, but I found something that looked plausible: A shared queue. I mentioned this when going over potential difficulties you may encounter without synchronizing, so this seems like a great way to learn how to make something thread-safe. On top of that, there'll be flipping between threads, unlike the clock program!
My first thought to making a couple of queues thread-safe was just to add the synchronized keyword to them all, but as it turns out, that adds a hell of a lot of unnecessary overhead to the program, and apparently the best way to deal with it is to create a wrapper class, so the overhead is only applied once. So let's get on with showing the start of a class to provide thread-safe access to a Queue:
TL;DR: Don't just blindly synchronize everything. This adds unnecessary overhead. Also, if you want this tl;dr to apply to everything so far, we're doing a synched queue :D
I'm starting off with an interface that I've had for a while, which actually took me longer to find than it would have done to rewrite one. The idea, as we've talked about (waaay back) is to implement methods and stuff automatically.
This is the wrapper class we'll (probably) be using. I made it implement Queue<T>, so that's how I got all the methods in. As part of the construction, we want to be using an actual queue, since this is just a wrapper, not the actual queue. All the methods consist of synchronizing the queue, then reapplying the method to it. Fairly simple, so far.
I made THIS class mostly for error checking, actually creating the queue. Couldn't name it Queue because the interface was already named that. Maybe I should've just not used the interface, after all :P Oh well!
This class should be very easy to understand, it's basically the stacks we've done before. It doesn't really do error checking too well, but that's not what we're interested in with this, so I won't bother making each method like 10 lines long.
I think that's quite a bit more than enough for one day, a Sunday, even, so that's all for now! See you tomorrow! Questions/comments welcome! Subscribe share blah blah blah, shameless plug, blah blah blah:
www.deltainterface.com for public domain works etc.