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.

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.

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.
No comments:
Post a Comment