Concurrency

Rule 7:Don’t depend on thread scheduleres

Any program that relies on the thread scheduler for CORRECNESS or PERFORMANCE is likely to be NON-PORTABLE.
because it’s on mercy of OS scheduler to pick the thread.

The best way to write a robust, responsive, portable program is to ensure that
the average number of runnable threads is not significantly greater than the number
of processors.

Note that the number of runnable threads isn’t the same as the total number of
threads, which can be much higher. Threads that are waiting are not runnable.

The main technique for keeping the number of runnable threads low is to have
each thread do some useful work, and then wait for more. Threads should not
run if they aren’t doing useful work. In terms of the Executor Framework, this means sizing thread pools appropriately and keeping
tasks short, but not too short, or dispatching overhead will harm performance.

Threads should not busy-wait, repeatedly checking a shared object waiting for
its state to change.busy-waiting greatly increases the load on the processor, reducing
the amount of useful work that others can accomplish.
The Problem with yield:
When faced with a program that barely works because some threads aren’t
getting enough CPU time relative to others, resist the temptation to “fix” the
program by putting in calls to Thread.yield.
The same yield
invocations that improve performance on one JVM implementation might make it
worse on a second and have no effect on a third. Thread.yield has no testable
semantics.

A better course of action is to restructure the application to reduce the
number of concurrently runnable threads.

In summary,
do not depend on the thread scheduler for the correctness of your
program. The resulting program will be neither robust nor portable. As a corollary,
do not rely on Thread.yield or thread priorities. These facilities are merely hints
to the scheduler. Thread priorities may be used sparingly to improve the quality of
service of an already working program, but they should never be used to “fix” a
program that barely works.

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment