Introduction
This is my 1300th post. At the time of my 1100th post, I feared that I would never make it to 1200, since the schools would be shut for the coronavirus and I'd never sub again.
But now that I've made it to 1300, I'm afraid that I won't make it to 1400. It's not that I'm having trouble finding work as a sub -- it's that I'm struggling to find work as a regular teacher. As I explained on the blog last month, I didn't always make the best choices inside and outside of the classroom. These decisions have weakened my resume, and so the human resources departments at most schools and districts will reject my application.
With my career at a dead end, I am considering a new job, perhaps coding in the Java language -- hence the reason for all of these Laura Lemay Java posts. And if I do launch a non-education career, then there will be no need for this education blog, and so I'll stop blogging. This could be before the 1400th post.
But before we get to Lemay and Java, let's start out with our Ian Stewart reading.
Calculating the Cosmos Chapter 18: The Dark Side
Chapter 18 of Ian Stewart's Calculating the Cosmos is called "The Dark Side." As usual, each chapter begins with a quote:
"There was nothing in the dark that wasn't there when the lights were on."
-- Rod Serling, The Twilight Zone, Episode 81: 'Nothing in the Dark.'
And here's how the chapter properly begins:
"Chapter 12 ended with the word 'oops.' It was a comment on the discovery that the rotation speeds of galaxies don't make sense."
OK, so it's been a year since we read Chapter 12, so I don't remember that final word. Anyway, this chapter is all about something invisible called "dark matter." In particular, it's believed that dark matter is the reason that galaxies spin faster away from the center, instead of more slowly as expected:
"There seems to be five times as much dark matter as normal matter, and in galactic-scale regions of the universe the mass of dark matter plus the effective mass of dark energy is twenty times the mass of normal matter."
And as it turns out, dark matter isn't just ordinary (jargon: Itbaryonic) matter that doesn't emit light -- instead, it's a new type of matter, made out of different particles. The Large Hadron Collider (LHC) is a particle accelerator that is used to search for new particles:
"This impressive apparatus recently made the epic observation of the Higgs boson, a particle that explains why many (but not all) particles have mass."
But unfortunately, the LHC found no dark matter particles. Perhaps dark matter consists of weakly interacting massive particles (or WIMPs) -- these might possibly be "supersymmetric" reflections of the particles we're already familiar with:
"This coincidence is known as the WIMP miracle. When the LHC began its observations, theorists hope it would see a whole raft of new supersymmetric partners of the known particles. Zilch."
Another possibility is that dark matter consists of "axions," which are also related by symmetry to previously known particles:
"Again, experimentalists have looked for them, but nothing convincing has been found. If none of the above, what else?"
At first it was once believed that there is something emitting gamma rays at the middle of our galaxy, perhaps some dark matter. But that only works if other galaxies emit gamma rays as well:
"According to Kevork Abazajian and Ryan Keeley, they don't. The smoking gun has turned out to be a damp squib."
There are other problems with the theory of dark matter. It only interacts with ordinary matter via gravity, yet gravity isn't enough to explain the spin rate of all galaxies:
"This kind of difficulty tends to be swept under the carpet, and questioning the existence of dark matter is treated as a form of heresy."
Still, perhaps there are other explanations for the motions of galaxies. For example, it could be that if acceleration is small enough, the formula F = ma fails:
"In the context of rotation curves, this assumption can also be reinterpreted as a slight change to Newton's law of gravity."
Meanwhile, it's been discovered that the amount of ordinary matter in the universe has been underestimated, until fairly recently:
"Not by enough to replace dark matter by ordinary matter, mind you -- but enough to require a rethink of all of the dark matter calculations. Such as the Bullet Cluster."
Indeed, a new theory involving symmetry in time removes the need for both dark energy and dark matter -- perhaps energy can go back in time and not just forward:
"According to this proposal, an initially homogeneous static universe would undergo an accelerating expansion as gravity amplifies quantum fluctuations."
And the author adds his own reasons why it's growing increasingly possible to describe the motions of galaxies without dark matter:
"But mathematicians are starting to question their assumptions that go into the Kepler equation, and their results, albeit incomplete, show that there's a case to answer."
The equations are difficult to solve, and so we make a simplifying assumption -- the stars in a galaxy form a sort of "star soup," with the "soup" forming a shell outside of the center of the galaxy:
"Independently of what the stars inside this shell are doing, we can apply Newton's theorem to concentrate their total mass as the center of the galaxy, without affective the overall force experienced by the test star."
But this is an oversimplification. Stars are discrete objects, and each the gravity of a passing star tugs at the test star, making it go faster:
"Of course that also slows the passing star down, but that's quickly replaced by another star, following along behind it."
So instead of a star soup, we approximate galaxies with "central configurations," with the galaxy resembling the wheel of a bike, with the stars lying on each spoke. These aren't exact models either:
"On the other hand, they're a reasonable choice for testing how the continuum and n-body models match up."
And at this point, Stewart includes his only diagram, of this type of a central configuration. Any number of spokes and rings are possible. The masses on each ring are equal but different rings can have different masses. The radii of the rings can be adjusted. For a given speed of rotation, masses can be chosen to suit given radii, or conversely. Variations on the spiderweb theme are also possible.
We now apply the n-body equations to this spiderweb:
"For example, if each star (hence each ring) has the same mass, central configurations exist, and the mass distribution is always less than a constant times the radius."
But this still produces grossly inaccurate results -- the masses of the outer rings are much, much less than given from the equations. So on this somber note, Stewart concludes the chapter:
"If dark matter exists, and forms vast, massive halos around galaxies, as astronomers think, then it can't actually explain the anomalous rotation curve that started the whole business. Either the law of gravity, or the traditional modeling assumptions, must be wrong."
EDIT Calculating the Cosmos Chapter 19: Outside the Universe
I am editing this post after the fact to include Chapter 19. This is because my copy of Eugenia Cheng's book finally arrived from the library. I was going to read Stewart until Cheng arrived and then return to Stewart after finishing Cheng. But I didn't realize that Cheng's book would arrive so late, and that there would be just one measly chapter of Stewart left. So instead, I'm editing in Stewart's last chapter so that we can make a clean transition from Stewart to Cheng.
Chapter 19 of Ian Stewart's Calculating the Cosmos is called "Outside the Universe." As usual, each chapter begins with a quote:
"Sometimes the Star Maker flung off creations which were in effect groups of many linked universes, wholly distinct physical systems of very different kinds."
-- Olaf Stapledon, Star Maker
And here's how the chapter properly begins:
"Why are we here? It's the ultimate philosophical question. Humans look through the windows of their eyes at a world far bigger and more powerful than they."
As the title and opening quote suggest, this chapter is all about the meaning of life, and what exists outside of the universe. According to physics, the origin of the universe is the Big Bang:
"Biology tells an even more convincing story of the origin of life and its evolution into the millions of species that inhabit the Earth today, us among them."
It's often pointed out how highly unlikely it is for all physical constants to have the correct values necessary for life to exist, and yet life exists:
"And that's a puzzle. Some religious people see this calculation as a proof of the existence of God, who has the luxury of selecting values of the fundamental constants that make life possible."
Stewart's solution is the possibility of a multiverse -- that is, there are many different universes and only a few of them support life. He tells us that most of this chapter is devoted to describing four different types of multiverse:
- Quilted multiverse: an infinite patchwork in which any region has a nearly exact copy somewhere else.
- Inflationary multiverse: whenever eternal inflation blows up the television and the cat, a new universe with different fundamental constants bubbles off.
- Landscape multiverse: a network of alternative universes linked by quantum tunneling, each obeying its own version of string theory.
- Quantum multiverse: a superposition of parallel worlds, each with its own separate existence. This is a universe version of Schrodinger's celebrated cat, both alive and dead at the same time.
The author begins with a quilted multiverse -- a universe so big that it's perhaps infinite, yet we can only see a finite part of it:
"The observable universe can do only finitely many different things. For simplicity, consider an infinite universe."
In this universe, doubles and near-doubles can exist, but your nearest double might be a googolplex light years away. Stewart moves on to the landscape universe -- if we make enough universes, we might stumble upon one with the right constants for life:
"Make even more, and the likely number of successes gets bigger. In any such universe -- and only those -- life can originate, evolve, get round to asking 'why are we here?', discover how improbable that is, and start worrying about it."
Both the landscape and inflationary multiverse are similar -- the difference is that landscape is based on string theory rather than inflation. If a string theory produces the right constants, the resulting universe can both produce life and itself be long-lived:
"How come suitability for life and longevity are associated? Lee Smolin has suggested an answer for the inflationary multiverse: new universes that bud off via black holes might evolve by natural selection, homing in on combinations of fundamental constants that not only make life possible, but give it plenty of time to get started and become more complex."
The author now moves on to the quantum universe. It is based on quantum mechanics, in which quantum states can be superposed or added:
"In classical physics, water waves do something similar: if two wave trains cross each other, their peaks add together to create bigger peaks, but a peak and a trough cancel out."
Stewart now describes the famous Schrodinger's cat experiment: according to quantum mechanics, it's possible to set up a box containing a cat such that the cat is "both alive and dead" until it is opened -- only then will the quantum state collapse so the cat can be one or the other. The quantum universe is similar to this:
"However, this time there's no way to open the box, because there's nothing outside the universe. So nothing can collapse the universe's quantum state."
In the multiverse, there's a universe where the cat is alive and another where the cat died. Some scientists try to find ways to escape the Schrodinger's cat paradox:
"Give the animal a mobile phone -- no, this is getting silly, and that would superimpose too. Anyway, it's an impermeable box."
One would think that an observation is like a mathematical function, which maps quantum states to their corresponding observations:
"What we have is a mismatch between an exact but intractable quantum representation of the measuring process, and an ad hoc add-on, the hypothetical function."
"More recently, physicists have been thinking about quantum observations from a genuinely quantum-mechanical point of view, instead of postulating unrealistic classical-type constraints."
For example, we can put photons and molecules in a superposition of states, but not yet a cat. And it's difficult to imagine an alternate universe in which Hitler won World War II:
"Even the particles that make him up would keep changing as he shed hair or picked up dust on his greatcoat."
And there are mathematical reasons why, even before we open the box, Schrodinger's cat is in an entangled state rather than a superposition of states, and so it's already either dead or alive:
"Which is what you'd expect from a classical model of the observational process, and isn't paradoxical. In 2015 Igor Pikowski, Magdalena Zych, Fabio Costa and Caslav Brukner introduced a new ingredient, finding that gravity makes superpositions decohere even faster."
And so, as Stewart explains, he is skeptical about whether multiverses can exist -- to him, it's just like assuming that the universe is geocentric and then giving convoluted reasons why the sun and stars are all moving around our planet at the same rate:
"The physicist Paul Steinhardt, who worked on inflation at its inception, made a similar point about the inflationary multiverse: 'In order to explain the one simple universe we can see, the inflationary multiverse hypothesis posits an infinite variety of universes with arbitrary amounts of complexity that we cannot see."
And so, we ask, how do we explain the apparent fine-tuning of the constants? In other words, what would happen to life if the constants were different?
"Broadly speaking, the method is to fix all of the fundamental constants except one, and find out what happens when that particular constant changes."
The author's analogy here involves a Ford Fiesta (which happens to be the car I bought last October). If we change the size of its bolts, the wheels don't stay on and the car can't move. Does this prove that the bolt size is a finely tuned constant, and so no other bolt size (not even on a different car) is possible?
"The mistake is to consider varying the constants one at a time. If you're building a car, you don't start with a design that works, and then change all the bolt sizes while leaving the nuts the same as before."
For example, stars can only exist if certain constants have certain values, but if we change those values slightly, more exotic yet starlike objects form instead.
"Why not allow more exotic objects to count as 'stars' too? Their energy output could still sustain a form of life."
Stewart ends the chapter by destroying the notion of merely a slim probability that the constants are all right for life:
"As far as stars go, our universe isn't battling odds of 10 million trillion trillion trillion to one against. It just called 'heads,' and the fundamental-constant coin landed that way up."
Stewart ends the book with an epilogue, which itself begins with a quote:
"The universe is a big place, perhaps the biggest."
-- Kilgore Trout (Philip Jose Farmer), Venus on the Half Shell
And the epilogue begins:
"Our mathematical journey has taken us from the surface of the Earth to the outermost reaches of the cosmos, and from the beginning of time to the end of the universe."
Yes, and scientists had to solve complicated equations to understand and model the universe -- and some of these equations are too difficult to solve:
"But progress was still possible. Poincare's ideas inspired an entirely new area of mathematics: topology."
And yes -- I described Poincare and topology previously on the blog, when we were side-along reading different books. (Poincare was the topic of our reading book from 2017, while in 2019 we read another book by Stewart himself where we discussed Poincare and the 2 1/2-to-3-body problem.)
"Scientists are constantly refining their understanding of the cosmos, and each new discovery raises fresh questions."
The author admits that he criticizes popular theories, from the Big Bang and dark energy/matter to today's multiverse theories. He doesn't want us readers to accept the standard theories blindly:
"On the other hand, I want to explain the conventional solutions too: they're beautiful applications of mathematics, they may well be right, and if not, they're paving the way towards something better."
And so Stewart concludes the book by supposing that just maybe, there was no Big Bang. Maybe there are no black holes, nor any dark matter.
"Maybe alien life can be radically different from anything we've ever encountered, possibly even than we can imagine. Maybe. Maybe not. The fun will be finding out."
Lemay Lesson 18: Multithreading
Here is the link to today's lesson:
http://101.lv/learn/Java/ch18.htm
Lesson 18 of Laura Lemay's Teach Yourself Java in 21 Days! is called "Multithreading." Here's how the chapter begins:
One of the major features in the Java programming environment and runtime system is the multithreaded architecture shared by both. Multithreading, which is a fairly recent construct in the computer science world, is a very powerful means of enhancing and controlling program execution. Today's lesson takes a look at how the Java language supports multithreading through the use of threads. You'll learn all about the different classes that enable Java to be a threaded language, along with many of the issues surrounding the effective use of threads.
To better understand the importance of threads, imagine that you're using your favorite text editor on a large file. When it starts up, does it need to examine the entire file before it lets you begin editing? Does it need to make a copy of the file? If the file is huge, this can be a nightmare. Wouldn't it be nicer for it to show you the first page, allowing you to begin editing, and somehow (in the background) complete the slower tasks necessary for initialization? Threads allow exactly this kind of within-the-program parallelism.
Perhaps the best example of threading (or lack of it) is a Web browser. Can your browser download an indefinite number of files and Web pages at once while still enabling you to continue browsing? While these pages are downloading, can your browser download all the pictures, sounds, and so forth in parallel, interleaving the fast and slow download times of multiple Internet servers? Multithreaded browsers can do all these things by virtue of their internal usage of threads.
I copied this entire opening because the concept of "threads" still confuses me. Of course, my Web browser can load several pages at once -- I call that "opening more than one tab." So I suppose in a way, a browser tab is like a thread.
The multithreading support in Java revolves around the concept of a thread. So what exactly is a thread? Put simply, a thread is a single stream of execution within a process. Okay, maybe that wasn't so simple. It might be better to start off by explaining exactly what a process is. A process is a program executing within its own address space. Java is a multiprocessing system, meaning that it supports many processes running concurrently in their own address spaces. You may be more familiar with the term multitasking, which describes a scenario very similar to multiprocessing. As an example, consider the variety of applications typically running at once in a graphical environment. Most Windows 95 users typically run a variety of applications together at once, such as Microsoft Word, CD Player, Windows Messaging, Volume Control, and of course Solitaire. These applications are all processes executing within the Windows 95 environment. So you can think of processes as being analogous to applications, or standalone programs; each process in a system is given its own space in memory to execute.
Of course, this just goes to show how old Lemay's text is. "Windows 95" isn't the latest version of Windows -- now Windows 10 is the standard, with Win 11 on its way. Meanwhile, "multitasking" has become so well-known that we now talk about people multitasking in real life.
If threading is so wonderful, why doesn't every system have it? Many modern operating systems have the basic primitives needed to create and run threads, but they are missing a key ingredient: The rest of their environment is not thread safe. A thread-safe environment is one that allows threads to safely coexist with each other peacefully. Imagine that you are in a thread, one of many, and each of you is sharing some important data managed by the system. If you were managing that data, you could take steps to protect it (as you'll see later today), but the system is managing it. Now visualize a piece of code in the system that reads some crucial value, thinks about it for a while, and then adds 1 to the value:
if (crucialValue > 0) { . . . // think about what to do crucialValue += 1; }
OK, I see -- you can't tell whether the variable is being incremented before or after what's happening on the other thread.
Getting used to threads takes a little while and a new way of thinking. Rather than imagining that you always know exactly what's happening when you look at a method you've written, you have to ask yourself some additional questions. What will happen if more than one thread calls into this method at the same time? Do you need to protect it in some way? What about your class as a whole? Are you assuming that only one of its methods is running at the same time?
This code shows a class used to count threads that suffers from the most pure form of the "synchronization problem": The += takes more than one step, and you may miscount the number of threads as a result. (Don't worry about how threads are created yet; just imagine that a whole bunch of them are able to call countMe(), at once, but at slightly different times.) Java allows you to fix this situation:
public class SafeThreadCounter { int crucialValue; public synchronized void countMe() { crucialValue += 1; } public int howMany() { return crucialValue; } }
OK, I sort of understand this.
The method howMany() in the last example doesn't need to be synchronized because it simply returns the current value of an instance variable. A method higher in the call chain-one that uses the value returned from howMany()- may need to be synchronized, though. Listing 18.1 contains an example of a thread in need of this type of synchronization.
Ah, finally -- there's a listing here:
Listing 18.1. The Point class.
1: public class Point { //redefines class Point from package java.awt 2: private float x, y; //OK since we're in a different package here 3: 4: public float x() { // needs no synchronization 5: return x; 6: } 7: 8: public float y() { // ditto 9: return y; 10: } 11: . . . // methods to set and change x and y 12: } 13: 14: public class UnsafePointPrinter { 15: public void print(Point p) { 16: System.out.println("The point's x is " + p.x() 17: + " and y is " + p.y() + "."); 18: } 19: }
But notice that this still isn't runnable code yet. The methods to set and change x and y need to be implemented, and there's no main method. Then again, this version is listed as Unsafe, so we're not supposed to run this code yet.
SafePointPrinter
The astute reader, though, may still be worried by the last example. It seems as if you made sure that no one executes your calls to x() and y() out of order, but have you prevented the Point p from changing out from under you? If the answer is no, you still have not completely solved the problem. It turns out that you really do need the full power of the synchronized statement:
public class SafePointPrinter { public void print(Point p) { float safeX, safeY; synchronized(p) { // no one can change p safeX = p.x(); // while these two lines safeY = p.y(); // are happening atomically } System.out.print("The point's x is " + safeX + " y is " + safeY); } }
Now you've got it! You actually needed to protect the Point p from changes, so you lock it by providing it as the argument to your synchronized statement.
And later on, the author shows us how to set the coordinates safely:
You can make sure it's okay by writing the only method that can change x and y inside p yourself:
public class Point { private float x, y; . . . // the x() and y() methods public synchronized void setXAndY(float newX, float newY) { x = newX; y = newY; } }
By making synchronized the only "set" method in Point, you guarantee that any other thread trying to grab the Point p and change it out from under you has to wait.
I admit that one problem I often have with C++ is remembering what methods and variables need to be labeled as const. These Java threads add a whole new level to making sure that values aren't changed when they're not supposed to be.
We also learn how to count threads safely:
Luckily, you now know the technique required to solve this:
public class StaticCounter { private static int crucialValue; public void countMe() { synchronized(getClass()) { // can't directly name StaticCounter crucialValue += 1; // the (shared) class is now locked } } }
The trick is to "lock" on a different object-not on an instance of the class, but on the class itself. Because a class variable is "inside" a class, just as an instance variable is inside an instance, this shouldn't be all that unexpected. In a similar way, classes can provide global resources that any instance (or other class) can access directly by using the class name and lock by using that same class name. In the last example, crucialValue was used from within an instance of StaticCounter, but if crucialValue were declared public instead, from anywhere in the program, it would be safe to say the following:
synchronized(Class.forName("StaticCounter")) { StaticCounter.crucialValue += 1; }
OK, so now we finally get to create our own threads:
Now that you understand the power (and the dangers) of having many threads running at once, how are those threads actually created?
Because there is a class java.lang.Thread, you might guess that you could create a thread of your own by subclassing it-and you are right:
public class MyFirstThread extends Thread { // a.k.a., java.lang.Thread public void run() { . . . // do something useful } }
And we can create a second thread as follows:
The interfaces you learned about on Day 16, "Packages and Interfaces," come to the rescue:
public class MySecondThread extends ImportantClass implements Runnable { public void run() { . . . // do something useful } }
By implementing the interface Runnable, you declare your intention to run in a separate thread. In fact, the Thread class is itself an implementation of this interface, as you might expect from the design discussions on Day 16. As you also might guess from the example, the Runnable interface defines only one method: run(). As in MyFirstThread, you expect someone to create an instance of a thread and somehow call your run() method.
The next listing is an example of creating and using threads:
Listing 18.2. The SimpleRunnable class.
1: public class SimpleRunnable implements Runnable { 2: public void run() { 3: System.out.println("in thread named '" 4: + Thread.currentThread().getName() + "'"); 5: } // any other methods run() calls are in current thread as well 6: } 7: 8: public class ThreadTester { 9: public static void main(String argv[]) { 10: SimpleRunnable aSR = new SimpleRunnable(); 11: 12: while (true) { 13: Thread t = new Thread(aSR); 14: 15: System.out.println("new Thread() " + (t == null ? 16: "fail" : "succeed") + "ed."); 17: t.start(); 18: try { t.join(); } catch (InterruptedException ignored) { } 19: // waits for thread to finish its run() method 20: } 21: } 22: }
Notice that since there are two classes and both of them are public, I had to define these in two different files, even though Lemay numbers the lines as if they were one file.
Because of the while(true) loop, this program generates infinitely many threads. Lemay writes:
Incidentally, Ctrl+C was pressed to interrupt the program, because it otherwise would continue on forever.
Unfortunately, Ctrl+C doesn't work on my computer, and neither does the Esc key, so I couldn't figure out how to stop it. Even running another program doesn't stop it -- the other program runs in its own thread, and then this one keeps generating new threads! I had to exit Java altogether in order to stop it.
Even though this is the final listing of the chapter, some of the other thread examples are instructive and runnable on the computer. The first example is just like 99 bottles of beer -- except instead of bottles of beer, they're threads.
NamedThreadTester
If you want your threads to have particular names, you can assign them yourself by using another form of Thread's constructor:
public class NamedThreadTester { public static void main(String argv[]) { SimpleRunnable aSR = new SimpleRunnable(); for (int i = 1; true; ++i) { Thread t = new Thread(aSR, "" + (100 - i) + " threads on the wall..."); System.out.println("new Thread() " + (t == null ? "fail" : "succeed") + "ed."); t.start(); try { t.join(); } catch (InterruptedException ignored) { } } } }
This version of Thread's constructor takes a target object, as before, and a string, which names the new thread. Here's the output:
new Thread() succeeded. in thread named '99 threads on the wall...' new Thread() succeeded. in thread named '98 threads on the wall...' new Thread() succeeded. in thread named '97 threads on the wall...'
Of course, this is also an infinite loop, since it says true in the for loop instead of an actual stopping condition -- maybe I should change it to i <= 100 so I don't have negative threads on the wall.
At this point Lemay discusses about how to tell when a thread has stopped. So far, my threads don't stop, so I don't need this. But here's what she writes:
In any case, SimpleRunnable is not a subclass of Thread, so how can this imagined example possibly catch the death of its thread? The answer is to use the following magic:
public class SingleThreadTester { public static void main(String argv[]) { Thread t = new Thread(new SimpleRunnable()); try { t.start(); someMethodThatMightStopTheThread(t); } catch (ThreadDeath aTD) { . . . // do some required cleanup throw aTD; // re-throw the error } } }
You understand most of this magic from yesterday's lesson.
Hey, that's right -- "yesterday" actually means yesterday here! This is the first time that I actually blogged two days in a row and did Java both days. Well, I am trying to get through Lemay's text -- again, reread what I wrote in the introduction to this 1300th post.
Let's move on to scheduling threads, an important concept:
You might be wondering how any software system can be truly threaded when running on a machine with a single CPU. If there is only one physical CPU in a computer system, it's impossible for more than one machine code instruction to be executed at a time. This means that no matter how hard you try to rationalize the behavior of a multithreaded system, only one thread is really being executed at a particular time. The reality is that multithreading on a single CPU system, like the systems most of us use, is at best a good illusion. The good news is that the illusion works so well most of the time that we feel pretty comfortable in the fact that multiple threads are really running in parallel.
The illusion of parallel thread execution on a system with a single CPU is often managed by giving each thread an opportunity to execute a little bit of code at regular intervals. This approach is known as timeslicing, which refers to the way each thread gets a little of the CPU's time to execute code. When you speed up this whole scenario to millions of instructions per second, the whole effect of parallel execution comes across pretty well.
The general task of managing and executing multiple threads in an environment such as this is known as scheduling. Likewise, the part of the system that decides the real-time ordering of threads is called the scheduler.
And, as the author tells us, there are two types of scheduling:
With nonpreemptive scheduling, the scheduler runs the current thread forever, requiring that thread to explicitly tell it when it is safe to start a different thread. With preemptive time slicing, the scheduler runs the current thread until it has used up a certain tiny fraction of a second, and then "preempts" it, suspends it, and resumes another thread for the next tiny fraction of a second.
OK, so what type of scheduling does my computer have?
To find out what kind of scheduler you have on your system, try out the following code:
public class RunnablePotato implements Runnable { public void run() { for (int i = 1; i <= 1300; ++i) System.out.println(Thread.currentThread().getName() + i); } } public class PotatoThreadTester { public static void main(String argv[]) { RunnablePotato aRP = new RunnablePotato(); new Thread(aRP, "one potato").start(); new Thread(aRP, "two potato").start(); } }
If your system employs a nonpreemptive scheduler, this code results in the following output:
one potato one potato one potato . . .
This output will go on forever or until you interrupt the program. For a preemptive scheduler that uses time slicing, this code will repeat the line one potato a few times, followed by the same number of two potato lines, over and over:
one potato one potato ... one potato two potato two potato ... two potato
As it turns out, my scheduler does neither of the above. Instead, it prints "one potato" several times, then "two potato" just once (not "the same number of lines"), and then more "one potato" several times before the second "two potato" and then more "one potato" lines.
Notice that I took Lemay's while(true) infinite loop out, and replaced it with a for loop with 1300 iterations (in honor of my 1300th post). I also had the values of i print so I could keep track. This is what my compiler displayed:
one potato1 one potato2 ... one potato29 two potato1 one potato30 ... one potato39And this was followed by "two potato2".
Interestingly enough, "two potato3" appears after "one potato74," then it's a string of "two potato" which actually takes the lead. In fact, "one potato75" doesn't appear until after "two potato337"! It then stays until "one potato529" and then it actually alternates "one potato" and "two potato" a short while.
What if you want to be sure the two threads will take turns, regardless of the type of system scheduler? You rewrite RunnablePotato as follows:
public class RunnablePotato implements Runnable { public void run() { while (true) { System.out.println(Thread.currentThread().getName()); Thread.yield(); // let another thread run for a while } } }
But this still doesn't work on my computer. It still gives strings of "one potato" and "two potato."
I also decided to try the priority tester, even though this will most likely be pointless:
To see whether thread priorities are working on your system, try this code:
public class PriorityThreadTester { public static void main(String argv[]) { RunnablePotato aRP = new RunnablePotato(); Thread t1 = new Thread(aRP, "one potato"); Thread t2 = new Thread(aRP, "two potato"); t2.setPriority(t1.getPriority() + 1); t1.start(); t2.start(); // at priority Thread.NORM_PRIORITY + 1 } }
If one potato is the first line of output, your system does not preempt using thread priorities.
Not only is "one potato1" my first line, but I don't see "two potato1" until after "one potato68." Well, that's so much for thread priorities!
Let's wrap up Java with the final listing:
Listing 18.3. The ComplexThread class.
1: public class ComplexThread extends Thread { 2: private int delay; 3: 4: ComplexThread(String name, float seconds) { 5: super(name); 6: delay = (int) seconds * 1000; // delays are in milliseconds 7: start(); // start up ourself! 8: } 9: 10: public void run() { 11: for (int i = 1; i <= 1300; ++i) {
12: System.out.println(Thread.currentThread().getName()); 13: try { 14: Thread.sleep(delay); 15: } catch (InterruptedException e) { 16: return; 17: } 18: } 19: } 20: 21: public static void main(String argv[]) { 22: new ComplexThread("one potato", 1.1F); 23: new ComplexThread("two potato", 1.3F); 24: new ComplexThread("three potato", 0.5F); 25: new ComplexThread("four", 0.7F); 26: } 27: }
As expected, it doesn't work properly. My compiler started with "one potato," "two potato," "three potato," "four," and then alternated "three potato" and "four" over and over. Not until all 1300 "three potato" and "four" have printed do "two potato" and "one potato" make their second appearance.
So in the end, it appears that threads are another thing that don't work properly on my computer.
Repost from Last Year: Akeelah and the Bee
Last night, after Zaila Avant-garde, an African-American girl, won the Scripps National Spelling Bee, she received a message from Keke Palmer -- the actress who played the title character from Akeelah and the Bee. Of course, the actress compared her own character to the actual champion:
“THE REAL LIFE AKEELAH YOU GUYS!! The real life one,” Palmer wrote Thursday on Instagram. “I’m so happy in my heart. A couple of weeks ago I sent in a video encouraging all the contestants and for this to happen just feels so spiritual! I am so happy.”
Palmer also quoted a line from the film. Professor Larabee, Akeelah's coach, gives this line during one of their training sessions:
“Our deepest fear is that we are powerful beyond measure. ... We ask ourselves, ‘Who am I to be brilliant, gorgeous, talented, fabulous?’ Actually, who are you not to be? ... We were born to make manifest the glory of God that is within us. ... And as we let our own light shine, we unconsciously give other people permission to do the same.”
In honor of Zaila's victory, let me repost what I wrote last year about the movie. I only wrote this last year due to the pandemic -- usually the bee is before the last day of school, and so I'm still focused on my actual classroom on the day of the bee. Also, since it's impossible to discuss the movie without mentioning race, let me protect myself with the "traditionalists" label.
Akeelah Anderson is a seventh grade girl at Crenshaw Middle School in Los Angeles. As the movie opens, we learn that she's an excellent speller. But she is caught ditching class by her principal, who threatens to make her attend summer school unless she signs up for the school spelling bee. (Recall that some of the runners in McFarland were similarly blackmailed into joining the school's Cross Country team.) She signs up and wins the school bee, thus advancing to the district spelling bee.
As I mentioned before, with all school movies, I'm on the lookout for calendar errors. At the start of the movie, Akeelah is described as an 11-year-old (who, as we find out later, is already in seventh grade because she's skipped a grade.) When Akeelah comes home from her school bee, she turns on ESPN that night and is intrigued by the Scripps National Spelling Bee, and she spends the entire film prepping for the following year's national bee. Thus one full year passes -- yet at the end of the film, she's described as still being 11 years old.
We also know that the real national spelling bee is just after Memorial Day. Yet the school bee -- which occurs on the same day as the (previous year's) national bee, occurs in April. And indeed, she spends about a month preparing for the district bee, which still takes place before summer vacation.
The top ten spellers at the district bee advance to the regional/state bee. Akeelah originally finishes in eleventh place, but qualifies for the regional bee anyway when another speller is caught cheating:
Cheater's Mom: He knew the word! I mean it's one we studied. He knew it.
Official: Ma'am, did you help your child spell the word? Ma'am, this is serious business.
Mom: Oh, you're damn right right it's serious! You are gonna give these kids ulcers. Do you know how long he has studied for this? He knew that word.
Boy: No, I didn't.
A major theme in this movie is race. Akeelah is a black girl who attends an inner-city school. At the district bee, her competitors are mostly of other races, including Javier, who is Hispanic, and Dylan, who is Chinese.
The Los Angeles neighborhoods mentioned in the movie are real, including the Crenshaw District, Beverly Hills, Santa Monica, and Woodland Hills. But there is no Crenshaw Middle School (though there is a high school by that name) -- the closest real middle school in that area is Audubon. And Beverly Hills and Santa Monica are separate cities with their own respective districts, so they wouldn't participate in the LAUSD district bee. But Woodland Hills, a suburb, really is part of LAUSD, so it's correct to have them compete in the district bee. It's in the San Fernando Valley, which is why Akeelah, who takes a long bus ride there to meet Javier and Dylan, sees "valley girls" sitting in a convertible.
Dylan is coached by his father, and recommends that Akeelah get a coach as well. Her coach is Josh Larabee, a retired professor from UCLA. (Go Bruins!) Over the summer, he teaches her that most words in English come from Latin or Greek, and so it's good for her to know her classical roots.
When she returns to school in the fall, Akeelah goes to the regional bee at USC (Boo Trojans!), where the top three qualify for the national bee. But she gets in trouble with her mother, who finds out that she's gone to the bee without permission. We learn that Akeelah's father has died of gun violence, and so her mother has her hands full with Akeelah and her older siblings -- her oldest brother is an Air Force pilot, her sister is herself a single parent, and the last brother is a gang member who is often escorted home by the cops. With all of this going on, the mother doesn't watch to deal with her youngest daughter and the bee. Right in the middle of the regional bee, she threatens to pull Akeelah from the competition.
The principal and Coach Larabee convince her mother to let the girl finish the bee. While all of this is going on, Javier, the last speller before it's Akeelah's turn, stalls for time in one of my favorite scenes of the film. He asks for the part of speech, origin, and example sentence for his word, and even asks for the word in a song. As it turns out, his word is ratatouille, a French vegetable dish -- and also, as it happens, it's the name of a Pixar film that came out the year after Akeelah. Most Pixar films contain many songs -- so if Javier had waited an extra year, he could have had the word ratatouille in an actual song!
Akeelah, Dylan, and Javier are the three qualifiers who advance to the national bee. At this point, I note the calendar again -- we know that it's now December because the newspaper that reports Akeelah's story mentions Kwanzaa (which, as I explained in previous posts, is an African-American holiday in December). Also, Akeelah buys Coach Larabee a Christmas present.
There's also especially poignant scene here where we learn that just as Akeelah has lost her father, Coach Larabee has lost a young daughter, Denise. Thus Akeelah and her coach end up seeing each other as a second family to make up for the loved ones that they've lost.
In the spring, Akeelah, her principal, coach, mother, oldest brother, and best friend Georgia all travel to Washington DC for the national bee:
Georgia: Oh, forget flight attendant. I'm gonna be a pilot! What's wrong with him (Javier)?
Akeelah: He has an aversion to heights.
Javier: It's an aversion to plummeting. I may puke.
Akeelah: My brother's in the Air Force and he says that fear is all in your head. Here. He gave me this (Air Force pin) for good luck. Don't worry, I won't impale you. You know, I never really thanked you for helping me at the state bee.
Javier: No biggie.
Akeelah: Actually, it was very chivalrous. (She kisses Javier on the cheek.)
Javier: Wow! I'm not thinking about the plane at all any more.
Akeelah: Well, in that case... (She opens the plane window.)
Here's a short montage from the national spelling bee:
Akeelah: The language of origin, please?
Javier: Any alternate pronunciations?
Jacques Bailey (the pronouncer from the real spelling bee): Gastromorph.
Dylan: May I have a definition, please?
Jacques: Latin.
Girl: Escharotie.
Javier: Madrigal.
Katie (bee announcer): That is correct.
Boy: May I have the definition, please?
Jacques: From earliest known time.
Boy: Aboriginally.
Katie: Correct.
Dylan: Language of origin? Empleomania.
Jacques: Any ratio without a separation of two phases.
Akeelah: M-I-S-C-I-B-L-E. Miscible.
Katie: If you're just joining us, we're in the eighth round of the national spelling bee with only thirty spellers remaining.
Earlier during their training, Coach Larabee tells Akeelah that she should study the winning words from previous competitions, and specifically mentions staphylococci, the 1987 winner. As it turns out, many of the words in the national bee in the movie are also winning words. Dylan's final word was logorrhea, the 1999 winner. And the 1995 winning word, also in the movie, was xanthosis.
After Javier finishes in fifth place, the next two go down quickly, leading to a final showdown between Akeelah and Dylan. At this point, Dr. Reilly began reading from the special list of 25 championship words.
There are several errors at this point. First of all, after Akeelah sees Dylan's overbearing coach/father, she wants to throw the competition for Dylan, knowing that it's his last chance to win while she can always try again next year. Dylan had finished second the previous year -- indeed, at the start of the movie when Akeelah turns on ESPN, she can see Dylan with his head turned down in shame as the winner is announced. But at that point, Akeelah was in seventh grade -- which means that she should now be in eighth grade, making it her last year of eligibility as well. (She had to go to summer school, but the "blackmail" agreement had been that training with Coach Larabee counted as summer school, so she advanced to the next grade.) The film probably should have started with Akeelah in sixth, not seventh, grade, for the scenes about "next year" to make sense.
The rules for the championship round are a little tricky -- partly because the rules have changed several times over the decades. It begins with Dylan spelling his first word, and then Akeelah misspells xanthosis, and then Dylan misspells xanthosis as well. It's explained that if a contestant misspells a word, the opponent must spell that same word plus an additional final word to win. This rule might have been in effect in the past, but not in the 21st century. Note that the championship words should begin when there are three spellers left, but the movie cleverly has the third and fourth place finishers be eliminated in the same round, so that there are only two spellers in the last rounds.
Indeed, it all depends on rounds. Dylan went first in his round, and so after Akeelah misspelled her word xanthosis, the round ends, and Dylan should have proceeded directly to his final word to win. If on the other hand, Dylan misspelled his first word, then since Akeelah hasn't gone yet in that round, she would have needed to spell her own word (xanthosis) plus her final word to win.
With two of the 25 words left to go, it's stated that if both spellers are correct with their respective words, they will be co-champions. At the time, the filmmakers couldn't have known what the actual rules for ties/co-champs are since it hadn't happened in decades (and under old rules), but the ties that occurred in the real spelling bees from 2014-16 reveal the actual tiebreaker rules.
First of all, suppose that Dylan misspelled the 24th word (logorrhea). Then Akeelah would have needed to spell her own word plus a final word -- but there was only one word left. Likewise, if Dylan had been correct but Akeelah incorrect, Dylan would have needed to spell a final word. So because of this, Dylan and Akeelah should have been declared co-champs after the 23rd word -- and this is what happened in 2014 and 2015. Instead, in the movie, Dylan was told that he had won the spelling bee before Akeelah was given her last word. This couldn't happen under the actual rules.
In 2016, the furor over back-to-back ties led to Scripps changing the tiebreaker rules -- instead of 25 words, there would be 25 rounds of championship words. Just like the old 25th word, the 25th round can only occur when there was only one speller left after the 24th round, so that the 25th round would consist of only the final word needed for that speller to win. Otherwise, co-champs would be declared after the 24th round -- which was exactly what happened again.
So in 2017 and 2018, a written tiebreaker test was given to all spellers before going on stage -- if after 25 rounds there were multiple spellers left, the test would determine the winner. But for some reason, that test wasn't given in 2019 -- and it was definitely needed. The bee took so long that they ended up declaring eight champions. I have no idea whether the championship word list was ever reached, as the field was never whittled down to a final three. Oh, and that year, each of the eight octochamps was declared a winner after he or she spelled the last word, just as (incorrectly) shown in the film. [2021 update: This year, the tiebreaker would have been the 90-second lightning round.]
The movie ends as Akeelah correctly spells her final word, pulchritude. She and Dylan are declared co-champs, and they both raise the trophy together. The film goes full-circle, as pulchritude (meaning "beauty") is the word that she misspelled on the day that she first met Coach Larabee.
If this movie were being made today, it might not have been set in LA. Last year at the real bee, it's revealed that there's a major spelling club, not in Woodland Hills, but in Dallas, Texas. And in fact, three of the eight octochamps were North Texan. Also, instead of making Dylan a Chinese character, his nationality would have been South Asian/Indian. Seven of the eight octochamps were of Indian descent, and South Asians have dominated the bee over the past decade or so.
On the other hand, Akeelah, unlike the heroes of Freedom Writers, McFarland, and Stand and Deliver, is not a real person. Sometimes I like to wish that there's a real Akeelah out there, all grown up and living a successful life after winning her prize, but there isn't. The closest there is to a real Akeelah is probably Jody-Anne Maxwell, the 1998 champion. She is a dark-skinned Jamaican who likely faced some of the same challenges that Akeelah does in the movie. [2021 update: Zaila, of course, is the real Akeelah.]
The movie has been criticized by some for its racial depictions -- Coach Larabee has been described as a "whitewashed" black man (especially when he becomes a grammar dictator who criticizes Akeelah's vernacular speech), and also, Dylan and his father have been said to represent negative stereotypes of Asian-Americans. Most likely, a Jody-Anne and the Bee film would have avoided both of these problems -- Jody-Anne's coach probably didn't criticize her Jamaican accent, and there might not have been any characters like Dylan or his dad. [2021 update: For that matter, a Zaila and the Bee movie would also work.]
But I would have been glad that it's an LA movie if I'd finished the year at my old charter school. At the end of the school year was eighth grade graduation, which all middle school teachers would have attended -- but then there would have been nothing for Grade 6-7 students to do. The usual thing to do in this situation is to leave a video for them to watch -- and I would have chosen Akeelah and the Bee, especially considering that it would have been the right time of year. I would hope that some of the Grade 6-7 kids would have seen themselves in Akeelah, since the charter school was located not far from where Akeelah is said to live. Her neighborhood in the movie is their real-life neighborhood.
Conclusion
There is an actual connection to traditionalists here -- I read that before she started spelling, Zaila was great at doing math problems in her head. It was her speed in doing arithmetic that inspired her father to have her transfer her mental powers from math to spelling. And obviously, it worked out in spades. OK, that's all I have to say about the spelling bee this year, so I don't need to drag it out further.
EDIT: We'll begin reading Eugenia Cheng's latest book in my next post.
No comments:
Post a Comment