Javamex

Java discussion forum to accompany the Javamex web site.

Hi Neil

First of all Neil, bravo for the site, its just amazing, i keep track of it from its early beginning , and it just gets better with every article.

I far as i understand, the best way to prevent a context switch,
(force my thread to use its quantum), is to run something like that
main(){
while(true){}
}
This program should not cause a lot of context switches.

And something really bad for context switching is
that two ( more) threads will increment a synchornized counter in a loop ?

Thanks

Views: 507

Reply to This

Replies to This Discussion

OK, so theoretically yes, if you just sit in a loop burning CPU, then you'll generally only context switch (a) every time your thread's quantum runs out (typically a few times a second) and/or (b) if another higher-priority thread needs a share of the CPU.

In your other case, it depends slightly. If the two threads are on the same CPU, it's actually not so bad in terms of context switches. Pretending for a moment that nothing else is running on that CPU, the two threads will just sit alternating, each updating the counter a few (million) times before the next thread gets its turn to do likewise. The lock won't be contended-- since the other thread can't possibly be running at the same time-- so neither thread will ever have to context-switch to wait for the lock.

If the two threads are running on different CPUs then this may cause more context switches, because it's possible that Thread A could be unlucky and try to acquire the lock at the split second that Thread B has it. Then, Thread A will have to "wait" for the lock. That means the JVM/OS could decide to context-switch at that point (whether this happens is JVM/OS specific, and may also depend on whether there's actually anything else waiting to run on that CPU).

I actually think the notion of "context switch" is bandied about a little too much. Doing a context switch per se is really no big deal-- your OS is probably doing hundreds or thousands of them per second as you speak, and the impact of a context switch really depends on what the context-switched threads are doing and how they could impact one another. A "context switch" is really quite a low-level thing for you to be worrying about in your app. I'd re-frame your concerns in terms of contention for locks and resources, for example.

Neil

Reply to Discussion

RSS

© 2024   Created by Neil Coffey.   Powered by

Badges  |  Report an Issue  |  Terms of Service