Avoid Java threading gotchas

Daily Newsletters

Sign up to ZDNet UK's daily newsletter.

ANALYSIS
Threading in programming languages is not a new idea. Having multiple points of execution is a concept that's fundamental to any multitasking environment. Java, however, requires developers to use explicit threading to accomplish tasks as basic as reading using nonblocking I/O. This reliance on threading for simple functions has developers working with Java threads while they're still learning the language. Unfortunately, if Java is their first language, this can mean threading before they're ready. Let's look at some of the gotchas that can sneak in while using threads. Unsynchronised wait()
This is a quickie that everyone hits the first time they try to use wait. Listing A shows a wait call being made on an arbitrary object. The code compiles and will run fine right up until the wait call, at which point it will throw an IllegalMonitorStateException. Before calling the wait method on an object, you must first obtain that object's monitor by enclosing the wait call in a synchronised block. An example of this is shown in Listing B. Fortunately, this gotcha is easy to catch; the exception gives it away. Most threading errors aren't so nice and fail intermittently or deadlock silently. Let's look at a few of those next. Unsynchronised exit conditions
A common use of threads is for a looping dispatch or processor thread. These threads loop infinitely waiting for an external thread to alter the state of a mutually accessible object. However, if care is not taken to synchronise the object both threads are accessing, some subtle deadlocks can occur. In Listing C, you see a processor thread that loops until the done Boolean is set to true. It's clear that the author of the code intends for some external thread to toggle the done flag to true and have the loop exit at the end of its current iteration. But you might get tripped up with the propagation of the state of the Boolean variable, done, across thread boundaries. The Java memory model makes no guarantee that changes made to done in one thread are reflected in another. Thus, it is possible that the external thread could toggle the flag's state, but the while loop in the other thread loops forever. Seasoned developers may now be saying that they've used code just like that seen in Listing C, and it works fine. They're right; usually it works just fine. However, there's no guarantee that it will always work as expected, and every experienced developer knows how Murphy's law applies to important events and intermittent failure. The Java memory model requires that variable state be correct after a synchronisation barrier has been encountered. This can be used to eliminate the risk of an infinitely looping processor thread, as shown in Listing D. The well-read Java developer might wonder whether the volatile keyword could be used to fix the same problem. The volatile keyword was created for just this sort of situation and was intended to force memory reads when accessing stale data in case a variable was updated in another thread. Unfortunately, the Java Language Specification was insufficiently detailed when addressing the workings of volatile, and many virtual machines ignore the keyword entirely.

Post your comment

In order to post a comment you need to be registered and logged in.

You can also log in with Facebook. Log in or create your ZDNet UK account below

  • Login

Will not be displayed with your comment

By signing up for this service, you indicate that you agree to our Terms and Conditions and have read and understood our Privacy Policy. Questions about membership? Find the answers in the Community FAQ

Get ZDNet UK's daily newsletter

Enter your email address to sign up

ZDNet UK Live

JCB33

How dare film makers, artists or anybody that invests in creativity stop us pirating their works for free. I want to be able to walk into my local...

5 hours ago by JCB33 on ACTA stumbles in Germany
Moley

@GrueMaster. I prefer horses for courses rather than one size fits all. I, and I suspect most other computer users, do not really wish to have...

7 hours ago by Moley on A tale of two distros: Ubuntu and Linux Mint
greycynic

The product that scares me every time I have to use it is the Office 2007 version of Excel. The first bug that I found was applying the median...

7 hours ago by greycynic on Ten flawed products that derail productivity
GrueMaster

Nice review and very informative. One thing I'd like to add (in reply to whs001's 1st question), the main reason to have the same interface from...

9 hours ago by GrueMaster on A tale of two distros: Ubuntu and Linux Mint
Frederick Wrigley

I'be been using Mint 12 since the RC came out, and I am far more happy with the Cinnamon, the Mate, and, yes (with extensions), theGnome 3...

9 hours ago by Frederick Wrigley via Facebook on A tale of two distros: Ubuntu and Linux Mint
bdantas

Excellent article. One small correction, though--although a fresh installation of Linux Mint 12 will, indeed, provide the user with a version of...

10 hours ago by bdantas on A tale of two distros: Ubuntu and Linux Mint
Alan Ralph

In related news, the ISPs club together to get the members of the Home Affairs Select Committee (ya goofed on that part, ZDNet UK) copies of "The...

11 hours ago by Alan Ralph via Facebook on MPs urge ISPs to take down terrorist material
Alan Ralph

In related news, the ISPs club together to get the members of the Home Affairs Select Committee (ya goofed on that part, ZDNet UK) copies of "The...

11 hours ago by Alan Ralph via Facebook on MPs urge ISPs to take down terrorist material
Moley

For Gnome 2 die-hards, it is possible to add icons to the bottom panel (or top top panel, if you prefer) which provide the exact Gnome 2...

11 hours ago by Moley on A tale of two distros: Ubuntu and Linux Mint
ramwellian

Your comments would seem pretty naive and immature. Your 'solution' appears to be, "gee, let's all just give in to the hackers and give them...

12 hours ago by ramwellian on Cloud computing security: no more oxymoron?
BugStalker

"Interesting thought ... If you installed Win7 as a dual boot on a machine that previously only had Linux, and it wrecked your Linux installation,...

12 hours ago by BugStalker on Windows 7 Declares War on GRUB
whs001

This is an excellent summary of Ubuntu and Mint and the interface differences between them. Most such articles take a very partisan position for...

12 hours ago by whs001 on A tale of two distros: Ubuntu and Linux Mint
Moley

@ewallace. Not so clear. Anyone can obtain the text, for example from here http://www.ustr.gov/webfm_send/2379. I support ACTA so long as it and...

12 hours ago by Moley on ACTA: Facts, misconceptions and questions
45283

I think WinRT is fantastic. I just wish it was an option for people that didn't want to go through Microsoft's App Store with its attendant...

15 hours ago by 45283 on Why Windows 8 needs architectural hygiene for WOA
Burn-IT

Nine people? £30m? Who's back pocket is that lot going in? And IF they say it is for new buildings, what about all the ones the government has...

16 hours ago by Burn-IT on Police set to launch three £30m e-crime hubs
ewallace

Just to be clear, nobody knows what is in the text of ACTA, here is a photograph of the text of ACTA http://twitpic.com/8h9iju as submitted to the...

17 hours ago by ewallace on ACTA: Facts, misconceptions and questions
fgvrg56

Unfortunately main issue is that ASUS is refusing to accept that they make some mistake on this version of asus Transformer prime. 1 - GPS sensor...

18 hours ago by fgvrg56 on Asus Eee Pad Transformer Prime Wi-Fi & GPS problems?
Ben Woods

@Marcus A fair question. Just talked with Archos which said it was working on an announcement for next week....

19 hours ago by Ben Woods on Archos confirms G9 Ice Cream Sandwich update schedule
Marcus Karlsson

Any update on this, considering the claimed "first week of February"?

20 hours ago by Marcus Karlsson via Facebook on Archos confirms G9 Ice Cream Sandwich update schedule
apexwm

Bill Goodrich : Just as al_langevin pointed out, with Windows Server 2008 there is no Services for Macintosh anymore. It's gone, not available....

1 day ago by apexwm on Windows Server 2008 drops the ball for Mac compatibility

Latest in Application Development