Results 1 to 5 of 5
  1. #1
    sebo is offline Member
    Join Date
    Oct 2008
    Posts
    9
    Rep Power
    0

    Question [SOLVED] Blocking Queues - how?

    Hi. I've got some small prog as you can see here... There are locks used in it.
    I want to understand the difference and the purpose of using blocking queues that's why i'd like to have this prog using them.
    Can anybody be so helpful to do this for me or just to give some tips how to start with this issue?
    Thx in advance!
    Java Code:
    import java.util.concurrent.locks.*;
    
    class Text {
    
      Lock lock = new ReentrantLock();
      Condition txtWritten = lock.newCondition();
      Condition txtSupplied = lock.newCondition();
    
      String txt = null;
      boolean newTxt = false;
    
      void setTextToWrite(String s) {
        lock.lock();
        try {
          if (txt != null) {
            while (newTxt == true)
              txtWritten.await();
          }
          txt = s;
          newTxt = true;
          txtSupplied.signal();
        } catch (InterruptedException exc) {
        } finally {
             lock.unlock();
        }
      }
    
       String getTextToWrite() {
         lock.lock();
         try {
           while (newTxt == false)
             txtSupplied.await(); // can be Interrupted
           	 newTxt = false;
             txtWritten.signal();
             return txt;
         } catch (InterruptedException exc) {
             return null;
         } finally {
             lock.unlock();
         }
       }
    }
    Java Code:
    class Author extends Thread {
    
    	  Teksty txtArea;
    
    	  Author(Teksty t)  {
    	    txtArea=t;
    	  }
    
    	  public void run() {
    
    	    String[] s = { "One", "Two", "Three", "Four", "Five", "Six", null };
    	    for (int i=0; i<s.length; i++) {
    	      try {
    	        sleep((int)(Math.random() * 1000));
    	      } catch(InterruptedException exc) { }
    	      txtArea.setTextToWrite(s[i]);
    	    }
    	  }
    }
    Java Code:
    class Writer extends Thread {
    
    	  Teksty txtArea;
    
    	  Writer(Teksty t) {
    	    txtArea=t;
    	  }
    
    	  public void run() {
    	    String txt = txtArea.getTextToWrite();
    	    while(txt != null) {
    	      System.out.println("-> " + txt);
    	      txt = txtArea.getTextToWrite();
    	      }
    	  }
    }
    Java Code:
    public class Coord {
    
    	   public static void main(String[] args) {
    	     Teksty t = new Teksty();
    	     Thread t1 = new Author(t);
    	     Thread t2 = new Writer(t);
    	     t1.start();
    	     try { Thread.sleep(3000); } catch(Exception exc) {}
    	     t2.start();
    	   }
    }

  2. #2
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Lightbulb spin locks

    Reading the docs it becomes obvious the purpose of such a class ( interface in the example provided in the docs ) would be to avoid what is called a spin-lock, or sometimes a hard-spin.

    What a hard-spin amounts to is spending too much processor resources trying to attain locking on an object such that the object never gets any work done, thus the lock is "spinning" so hard on what it is trying to achieve that what results is the machine sitting there doing nothing, possibly unresponsive to user control. The really bad part about that is trying to recover control of the machine is virtulally impossible.

    You can code the general solution along the lines you are working towards, but one should check a control variable before the sleep or after. Correctly, a yield() should allow the os to allocate processor power but we cannot rely on that due to the fact that we do not write the scheduler.

    My suggestion for a place to start would be to design a code structure that will read System.in without blocking. Remarkable, but it can be done though people will tell you that it cannot.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  3. #3
    sebo is offline Member
    Join Date
    Oct 2008
    Posts
    9
    Rep Power
    0

    Default

    K, this is what i did:
    Java Code:
    import java.util.concurrent.BlockingQueue;
    import java.io.PrintStream;
    
    public class Author extends Thread
    {
      private BlockingQueue<String> blockingQueue;
      private PrintStream printStream;
      private String[] s;
      private int i = 0;
    
      public Author(String[] s, BlockingQueue<String> blockingQueue, PrintStream printStream) {
        this.s = s;
        this.printStream = printStream;
        this.blockingQueue = blockingQueue;
      }
    
      public void run()
      {
        try
        {
          while(i<s.length) {
            printStream.println("Putting '"+s[i]+"' on BlockingQueue.");
            blockingQueue.put(s[i++]);
            Thread.sleep(1500);
          }
        }    
        catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      
      public int getSize() {
    	  return s.length;
      }
    }
    Java Code:
    import java.util.concurrent.BlockingQueue;
    import java.io.PrintStream;
    
    public class Writer extends Thread {
      private BlockingQueue<String> blockingQueue;
      private PrintStream printStream;
      private Author author;
      int i=0;
      
      public Writer(BlockingQueue<String> blockingQueue, PrintStream printStream) {
        blockingQueue = this.blockingQueue;
        printStream = this.printStream;
      }
      
      public void run()
      {
    	try {
    		while (i++<author.getSize()) {
    			try {
    				[B][U]printStream.println("--> "+ blockingQueue.take());[/U][/B]               
    			}
    			catch (InterruptedException ie) {}           
    		}
    	}
    	catch (NullPointerException npe) {} 
      }
    }
    Java Code:
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.LinkedBlockingQueue;
    
    public class TestBlockingQueue
    {  	
      public static void main(String args[]) {
        String[] s = { "One", "Two", "Three", "Four", "Five", "Six" };
        BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>();
        Author author = new Author(s, blockingQueue, System.out);
        Writer writer = new Writer(blockingQueue, System.out);	
        author.start();
        try { Thread.sleep(1000); } catch(Exception exc) {}
        writer.start();
      }
    }
    This is the output:
    Putting 'One' on BlockingQueue.
    Putting 'Two' on BlockingQueue.
    Putting 'Three' on BlockingQueue.
    Putting 'Four' on BlockingQueue.
    Putting 'Five' on BlockingQueue.
    Putting 'Six' on BlockingQueue.

    The queue is being filled correctly, but the code i've put in bold seems not to be executed and i have no idea why, between every line ther should be sth like: --> One, --> Two etc.
    Does anybody see some mistake i probably did?

  4. #4
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default

    In the code above, you have a bug in the lines "blockingQueue = this.blockingQueue" and the following (should be the other way round). So inside your run() method, a NullPointerException will be being thrown that you're blindly ignoring. Some things you can do to spot these types of problems:

    - Declare instance variables final if you only expect them to be set once in the constructor; if you'd declared 'blockingQueue' and 'printStream' as final, the compiler would have spotted that you weren't setting it
    - DON'T SWALLOW EXCEPTIONS: in particular, if you get a NullPointerException, there's blatantly something wrong. Why are you even catching it in this case? With the InterruptedException, I'd generally recommend wrapping the WHOLE run() method with the try/catch for this: if somebody interrupts your thread, it's probably because they want it to stop, not because they want it to continue to the next iteration of the loop!

  5. #5
    sebo is offline Member
    Join Date
    Oct 2008
    Posts
    9
    Rep Power
    0

    Default

    yeah.. i must have been stoned or sth when writing this... and also because i was changing this few times there were some things i forgot to throw out...
    k, now it's just like it should be in the beginning! so i followed your tips and this NPE gives really the answer what's wrong in the code... my while statement was totally wrong - i've changed it to !blockingQueue.isEmpty() and put some sleep time so that it can wait a second until there is a new word in the queue.

    thx one more time for ur help!

Similar Threads

  1. Implementing a Stack Using two Queues
    By rhm54 in forum New To Java
    Replies: 3
    Last Post: 12-01-2010, 10:28 AM
  2. Help with Queues in Java
    By Java01 in forum New To Java
    Replies: 3
    Last Post: 11-07-2008, 03:56 PM
  3. [SOLVED] Site Blocking
    By Mir in forum Networking
    Replies: 12
    Last Post: 07-03-2008, 06:04 AM
  4. Replies: 1
    Last Post: 08-07-2007, 07:05 AM
  5. Non Blocking Network
    By mathias in forum Networking
    Replies: 1
    Last Post: 08-07-2007, 06:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •