1 46 47 package org.mr.kernel; 48 49 import org.mr.MantaException; 50 import org.mr.IMessageListener; 51 import org.mr.core.protocol.MantaBusMessage; 52 import org.mr.core.protocol.MantaBusMessageConsts; 53 54 63 public class BlockingMessageListener implements IMessageListener { 64 MantaBusMessage response = null; 65 MantaBusMessage returnResponse = null; 66 MantaBusMessage request; 67 String listenerString; 68 Object syncObject = new Object (); 69 70 public BlockingMessageListener(MantaBusMessage request){ 71 this.request = request; 72 } 73 74 public BlockingMessageListener(){ 75 76 } 77 78 81 public void onMessage(MantaBusMessage message) { 82 83 synchronized(syncObject){ 84 while (response != null) { 85 try { 86 syncObject.wait(); 87 } catch (InterruptedException e) { 88 e.printStackTrace(); 89 } 90 } 91 response = message; 92 syncObject.notifyAll(); 93 } 94 } 96 103 public MantaBusMessage waitForResponse(long timeout) throws InterruptedException , MantaException{ 104 if(request != null && request.getHeader(MantaBusMessageConsts.HEADER_NAME_SENT_FAIL) != null) 105 throw new MantaException("Failed to send request, no use to wait for response.",MantaException.ID_WAIT_FOR_RESPONSE_FAIL ); 106 107 synchronized(syncObject){ 108 if(response != null) { 109 return response; 110 } 111 if(response == null) { 112 syncObject.wait(timeout); 113 } 114 returnResponse = response; 115 response = null; 116 syncObject.notifyAll(); 117 } 118 return returnResponse; 119 } 120 121 122 125 public String getListenerString() { 126 return listenerString; 127 } 128 129 132 public void setListenerString(String listenerString) { 133 this.listenerString = listenerString; 134 } 135 136 } 137 | Popular Tags |