Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

See the code in criticalSectionExamples.zip in the sampleCode folder in the eLea

ID: 3558782 • Letter: S

Question

See the code in criticalSectionExamples.zip in the sampleCode folder in the eLearning site to answer this question.

Why does the output of the sample code CriticalSectionBroken.java fail to print correctly?


Generally, how do we correct this problem with a critical section?

code:

package criticalSection;


public class CriticalSectionBroken
{
   static String message = "Now Is The Time For All Good Men ";
   static int numThreads = 200;

   public static void main(String args[])
   {
       for (int idx = 0; idx < numThreads; idx++) {
           Thread t = new Thread(new StreamPrinter());
           t.start();
       }
   }

   static class StreamPrinter implements Runnable
   {
       @Override
       public void run()
       {
           while (true) {
               byte chars[] = message.getBytes();
               for (int idx = 0; idx < chars.length; idx++) {
                   byte achar = chars[idx];
                   System.out.write((char) achar);
                   Thread.yield();
               }
           }
       }
   }
}

Explanation / Answer

Because of this infinite loop

while (true) {
               byte chars[] = message.getBytes();
               for (int idx = 0; idx < chars.length; idx++) {
                   byte achar = chars[idx];
                   System.out.write((char) achar);
                   Thread.yield();
               }