Wednesday, 22 October 2008

Clean Code By Robert C. Martin - Part6

Couple of Days back i started reading Clean Code By Robert C. Martin

I wanted to share few important quotations i found from the next 3 chapters of the book (13-14-15).

1) The servlets are executed asynchronously whenever Web requests come in.

2) Some systems have response time and throughput constraints that require hand-coded concurrent solutions.For example, consider a single-threaded information aggregator that acquires information from many different Web sites and merges that information into a daily summary. Because this system is single threaded, it hits each Web site in turn, always finishing one before starting the next. The daily run needs to execute in less than 24 hours. However, as more and more Web sites are added, the time grows until it takes more than 24 hours to gather all the data. The single-thread involves a lot of waiting at Web sockets for I/O to complete.We could improve the performance by using a multithreaded algorithm that hits more than one Web site at a time.

3) Myths and Misconceptions

And so there are compelling reasons to adopt concurrency. However, as we said before,concurrency is hard. If you aren’t very careful, you can create some very nasty situations.

Consider these common myths and misconceptions:

• Concurrency always improves performance.

Concurrency can sometimes improve performance, but only when there is a lot of wait time that can be shared between multiple threads or multiple processors. Neither situation is trivial.

• Design does not change when writing concurrent programs.

In fact, the design of a concurrent algorithm can be remarkably different from the design of a single-threaded system. The decoupling of what from when usually has a huge effect on the structure of the system.

• Understanding concurrency issues is not important when working with a container such as a Web or EJB container.

In fact, we’d better know just what your container is doing and how to guard against the issues of concurrent update and deadlock.

4) Single Responsibility Principle

The SRP states that a given method/class/component should have a single reason to change. Concurrency design is complex enough to be a reason to change in it’s own right and therefore deserves to be separated from the rest of the code. Unfortunately, it is all too common for concurrency implementation details to be embedded directly into other production code.

Here are a few things to consider:

• Concurrency-related code has its own life cycle of development, change, and tuning.

• Concurrency-related code has its own challenges, which are different from and often more difficult than nonconcurrency-related code.

• The number of ways in which miswritten concurrency-based code can fail makes it challenging enough without the added burden of surrounding application code.

Recommendation: Keep your concurrency-related code separate from other code.

5) Corollary: Limit the Scope of Data

As we saw, two threads modifying the same field of a shared object can interfere with each other, causing unexpected behavior. One solution is to use the synchronized keyword to protect a critical section in the code that uses the shared object. It is important to restrict the number of such critical sections. The more places shared data can get updated, the more likely:

• You will forget to protect one or more of those places—effectively breaking all code that modifies that shared data.

• There will be duplication of effort required to make sure everything is effectively guarded (violation of DRY7).

• It will be difficult to determine the source of failures, which are already hard enough to find.

Recommendation: Take data encapsulation to heart; severely limit the access of any data that may be shared.

6) Corollary: Threads Should Be as Independent as Possible

Consider writing your threaded code such that each thread exists in its own world, sharing no data with any other thread. Each thread processes one client request, with all of its required data coming from an unshared source and stored as local variables. This makes each of those threads behave as if it were the only thread in the world and there were no synchronization requirements.

For example, classes that subclass from HttpServlet receive all of their information as parameters passed in to the doGet and doPost methods. This makes each Servlet act as if it has its own machine. So long as the code in the Servlet uses only local variables,there is no chance that the Servlet will cause synchronization problems. Of course,most applications using Servlets eventually run into shared resources such as database
connections.

Recommendation: Attempt to partition data into independent subsets than can be operated on by independent threads, possibly in different processors.

7) Know Your Execution Models

There are several different ways to partition behavior in a concurrent application. To discuss
them we need to understand some basic definitions.







Bound ResourcesResources of a fixed size or number used in a concurrent environment.Examples include database connections and fixed-size read/write buffers
Mutual ExclusionOnly one thread can access shared data or a shared resource at a time.
StarvationOne thread or a group of threads is prohibited from proceeding for an excessively long time or forever. For example, always letting fast-running threads through first could starve out longer running threads if there is no end to the fast-running threads
DeadlockTwo or more threads waiting for each other to finish. Each thread has a resource that the other thread requires and neither can finish until it gets the other resource.
LivelockThreads in lockstep, each trying to do work but finding another "in the way." Due to resonance, threads continue trying to make progress but are unable to for an excessively long time—or forever.


8) Concurrent code is difficult to get right. Code that is simple to follow can become nightmarish when multiple threads and shared data get into the mix. If you are faced with writing concurrent code, you need to write clean code with rigor or else face subtle and infrequent failures.

First and foremost, follow the Single Responsibility Principle. Break your system into POJOs that separate thread-aware code from thread-ignorant code. Make sure when you are testing your thread-aware code, you are only testing it and nothing else. This suggests that your thread-aware code should be small and focused.

Know the possible sources of concurrency issues: multiple threads operating on shared data, or using a common resource pool. Boundary cases, such as shutting down cleanly or finishing the iteration of a loop, can be especially thorny.

9) Run on Different Platforms

In the middle of 2007 we developed a course on concurrent programming. The course development ensued primarily under OS X. The class was presented using Windows XP running under a VM. Tests written to demonstrate failure conditions did not fail as frequently in an XP environment as they did running on OS X.
In all cases the code under test was known to be incorrect. This just reinforced the fact that different operating systems have different threading policies, each of which impacts the code’s execution. Multithreaded code behaves differently in different environments.You should run your tests in every potential deployment environment. Recommendation: Run your threaded code on all target platforms early and often.

About the Author

Robert C. Martin is a principal in a consulting firm named Object Mentor, based in Illinois. Object Mentor provides software leadership services to the global community. They use XP process improvement, OO design consulting, and the skills that come with experience to help companies get their projects done.

8 comments:

Anonymous said...

I don't even know the way I finished up here, however I believed this put up used to be great. I don't recognize who you're however certainly you're going to a
well-known blogger for those who are not already.
Cheers!

Look at my web site :: know More

Anonymous said...

I am extremely impressed with your writing skills as
well as with the layout on your weblog. Is this
a paid theme or did you customize it yourself? Anyway keep up the excellent quality writing, it is rare to see a nice blog like this
one nowadays.

my site; costing Gauteng

Anonymous said...

What's up, everything is going fine here and ofcourse every one is sharing information, that's actually fine,
keep up writing.

Here is my website door to door delivery Gauteng

Anonymous said...

Wow that was strange. I just wrote an extremely
long comment but after I clicked submit my comment didn't appear. Grrrr... well I'm not writing
all that over again. Anyways, just wanted to say
superb blog!

Feel free to visit my weblog - hair salon Parktown North
my site > hairdresser Parktown North

Anonymous said...

Simply desire to say your article is as astounding.
The clarity on your put up is simply great and that i can assume you're a professional on this subject. Well with your permission allow me to grasp your RSS feed to stay up to date with approaching post. Thank you a million and please carry on the gratifying work.

My webpage - identity design Western Cape
Also see my webpage > branding

Anonymous said...

Thanks for another wonderful post. The place else could anybody get that type of info in such a
perfect approach of writing? I've a presentation subsequent week, and I'm at the look for such info.



Here is my homepage - more info

Anonymous said...

Incredible story there. What occurred after? Take care!


Also visit my web-site ... more information

Anonymous said...

I blog quite often and I genuinely appreciate your information.
The article has truly peaked my interest. I will take a note of your website and keep checking for new details about once a week.
I opted in for your RSS feed as well.

Also visit my web-site ... visit link