List of usage examples for java.lang Thread wait
public final native void wait(long timeoutMillis) throws InterruptedException;
From source file:Main.java
public static void wait(Thread thread, int seconds) { try {/* w w w. ja v a 2 s.c o m*/ thread.wait(seconds * 1000); } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:grails.plugin.cache.redis.GrailsRedisCache.java
protected boolean waitForLock(RedisConnection connection) { boolean foundLock = false; boolean retry = true; while (retry) { retry = false;// w w w .j a v a 2 s . c o m if (connection.exists(cacheLockName)) { foundLock = true; try { Thread thread = Thread.currentThread(); synchronized (thread) { thread.wait(WAIT_FOR_LOCK); } } catch (InterruptedException ex) { // ignore } retry = true; } } return foundLock; }
From source file:de.hpi.i2b2.girix.GIRIXService.java
private OMElement execute(RequestHandler handler, RequestMessageType message) throws I2B2Exception { // Extract wait time. If no waitTime is given it defaults to 0 which is equivalent to an infinite waitTime long waitTime = 0; if (message.getRequestHeader() != null) { waitTime = message.getRequestHeader().getResultWaittimeMs(); }/*w w w .j ava 2s . c o m*/ // Do query processing inside thread, so that service could send back message with timeout error String unknownErrorMessage = "Error message delivered from the remote server: Unknown exception. See log file for stack trace."; ExecutorRunnable er = new ExecutorRunnable(); er.setInput(message); er.setRequestHandler(handler); Thread t = new Thread(er); String girixDataResponse = null; // Start thread... synchronized (t) { t.start(); // ...meanwhile in main thread: count time and check for timeout try { long startTime = System.currentTimeMillis(); long deltaTime = -1; while ((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { if (waitTime > 0) { t.wait(waitTime - deltaTime); deltaTime = System.currentTimeMillis() - startTime; } else { // wait until job is completed t.wait(); } } // Now try to extract the result... girixDataResponse = er.getOutputString(); // ...which is null if there was an error if (girixDataResponse == null) { // Error case 1: There was an exception during thread execution if (er.getJobException() != null) { // Error case 1.1: Causing exception was set -> Default unknown error message & logging stack trace if (er.getJobException().getCause() != null) { log.error("Exception stack trace:\n" + GIRIXUtil.getStackTraceAsString(er.getJobException())); ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null, unknownErrorMessage); girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType); } else { // Error case 1.2: Causing exception wasn't set -> Custom error message. Logging is done by throwing method ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null, er.getJobException().getMessage()); girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType); } // Error case 2: Timeout } else if (er.isJobCompleteFlag() == false) { String timeOuterror = "Remote server timed out \nResult waittime = " + waitTime + " ms elapsed\nPlease try again"; log.error(timeOuterror); log.debug("girix waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null, timeOuterror); girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType); // Error case 3: Result was set to null by the thread } else { log.error("girix data response is null"); log.debug("girix waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); ResponseMessageType responseMsgType = MessageUtil.doBuildErrorResponseMessageType(null, "Error message delivered from the remote server: Result was set to null."); girixDataResponse = MessageUtil.convertResponseMessageTypeToXML(responseMsgType); } } } catch (InterruptedException e) { log.error(e.getMessage()); throw new I2B2Exception("Thread error while running GIRIX job"); } finally { t.interrupt(); er = null; t = null; } } // Send back answer. girixDataResponse contains either an error message or the proper response if there was no critical error return MessageUtil.convertXMLToOMElement(girixDataResponse); }
From source file:edu.harvard.i2b2.pm.ws.PMService.java
/** * This function is main webservice interface to get pulmonary data from * pulmonary report. It uses AXIOM elements(OMElement) to conveniently parse * xml messages./*from w ww.j ava 2 s . c om*/ * * It excepts incoming request in i2b2 message format, which wraps PFT * report inside patientdata object. The response is also will be in i2b2 * message, which will wrap patientdata object. Patient data object will * have all the extracted pft concepts from the report. * * * @param getServices * @return OMElement in i2b2message format * @throws PortletServiceNotFoundException * @throws PortletServiceUnavailableException * @throws Exception */ public OMElement getServices(OMElement getPMDataElement) throws I2B2Exception { /* OMElement returnElement = null; String pmDataResponse = null; String unknownErrorMessage = "Error message delivered from the remote server \n" + "You may wish to retry your last action"; if (getPMDataElement == null) { log.error("Incoming PM request is null"); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); pmDataResponse = MessageFactory.convertToXMLString(responseMsgType); return MessageFactory.createResponseOMElementFromString(pmDataResponse); } ServicesMessage servicesMsg = new ServicesMessage(getPMDataElement.toString()); // String requestElementString = getPMDataElement.toString(); // childrenDataMsg.setRequestMessageType(requestElementString); long waitTime = 0; if (servicesMsg.getRequestMessageType() != null) { if (servicesMsg.getRequestMessageType().getRequestHeader() != null) { waitTime = servicesMsg.getRequestMessageType() .getRequestHeader() .getResultWaittimeMs(); } } //do Workplace query processing inside thread, so that // service could send back message with timeout error. ExecutorRunnable er = new ExecutorRunnable(); return er.execute(new ServicesHandler(servicesMsg), waitTime); */ OMElement returnElement = null; if (getPMDataElement == null) { log.error("Incoming PM request is null"); throw new I2B2Exception("Incoming PM request is null"); } Pattern p = Pattern.compile("<password>.+</password>"); Matcher m = p.matcher(getPMDataElement.toString()); String outString = m.replaceAll("<password>*********</password>"); p = Pattern.compile(">.+</ns9:set_password>"); m = p.matcher(outString); outString = m.replaceAll(">*********</ns9:set_password>"); log.debug("Received Request PM Element " + outString); log.debug("Begin getting servicesMsg"); ServicesMessage servicesMsg = new ServicesMessage(getPMDataElement.toString()); long waitTime = 0; if (servicesMsg.getRequestMessageType() != null) { if (servicesMsg.getRequestMessageType().getRequestHeader() != null) { waitTime = servicesMsg.getRequestMessageType().getRequestHeader().getResultWaittimeMs(); } } log.debug("Completed getting servicesMsg, waittime is: " + waitTime); //do PM processing inside thread, so that // service could sends back message with timeout error. String pmDataResponse = null; try { ExecutorRunnable er = new ExecutorRunnable(); //er.setInputString(requestElementString); log.debug("begin setRequestHandler, my servicesMsg: " + servicesMsg); er.setRequestHandler(new ServicesHandler(servicesMsg)); log.debug("middle setRequestHandler"); log.debug("end setRequestHandler"); Thread t = new Thread(er); ResponseMessageType responseMsgType = null; synchronized (t) { t.start(); try { //if (waitTime > 0) { // t.wait(waitTime); //} else { // t.wait(); //} long startTime = System.currentTimeMillis(); long deltaTime = -1; while ((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { if (waitTime > 0) { t.wait(waitTime - deltaTime); deltaTime = System.currentTimeMillis() - startTime; } else { t.wait(); } } pmDataResponse = er.getOutputString(); if (pmDataResponse == null) { if (er.getJobException() != null) { pmDataResponse = ""; throw new I2B2Exception("Portal is not property configured."); } else if (er.isJobCompleteFlag() == false) { String timeOuterror = "Result waittime millisecond <result_waittime_ms> :" + waitTime + " elapsed, try again with increased value"; log.debug(timeOuterror); responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); pmDataResponse = MessageFactory.convertToXMLString(responseMsgType); } } } catch (InterruptedException e) { log.error("Error in thread: " + e.getMessage()); e.printStackTrace(); throw new I2B2Exception("Thread error while running PM job " + getPMDataElement, e); } finally { t.interrupt(); er = null; t = null; } } } catch (Exception e) { log.error("Error: " + e.getMessage()); e.printStackTrace(); } try { returnElement = MessageFactory.createResponseOMElementFromString(pmDataResponse); log.debug("my pm repsonse is: " + pmDataResponse); log.debug("my return is: " + returnElement); } catch (XMLStreamException e) { log.error("Error creating OMElement from response string " + pmDataResponse, e); } return returnElement; }
From source file:edu.harvard.i2b2.im.ws.IMService.java
private OMElement execute(RequestHandler handler, long waitTime) throws I2B2Exception { //do workplace processing inside thread, so that // service could send back message with timeout error. log.debug("In execute"); OMElement returnElement = null;/*from w ww. ja v a2 s. c o m*/ String unknownErrorMessage = "Error message delivered from the remote server \n" + "You may wish to retry your last action"; ExecutorRunnable er = new ExecutorRunnable(); er.setRequestHandler(handler); Thread t = new Thread(er); String workplaceDataResponse = null; synchronized (t) { t.start(); // try { // if (waitTime > 0) { // t.wait(waitTime); // } else { // t.wait(); // } try { long startTime = System.currentTimeMillis(); long deltaTime = -1; while ((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { if (waitTime > 0) { t.wait(waitTime - deltaTime); deltaTime = System.currentTimeMillis() - startTime; } else { t.wait(); } } workplaceDataResponse = er.getOutputString(); if (workplaceDataResponse == null) { if (er.getJobException() != null) { log.error("er.jobException is " + er.getJobException().getMessage()); log.info("waitTime is " + waitTime); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); } else if (er.isJobCompleteFlag() == false) { //<result_waittime_ms>5000</result_waittime_ms> String timeOuterror = "Remote server timed out \n" + "Result waittime = " + waitTime + " ms elapsed,\nPlease try again"; log.error(timeOuterror); log.debug( "im waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); } else { log.error("im data response is null"); log.info("waitTime is " + waitTime); log.debug( "im waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); } } } catch (InterruptedException e) { log.error(e.getMessage()); throw new I2B2Exception("Thread error while running IM job "); } finally { t.interrupt(); er = null; t = null; } } returnElement = MessageFactory.createResponseOMElementFromString(workplaceDataResponse); return returnElement; }
From source file:edu.harvard.i2b2.crc.ejb.QueryManagerBeanUtil.java
public Map testSend(String domainId, String projectId, String ownerId, String generatedSql, String sessionId, String queryInstanceId, String patientSetId, String xmlRequest, long timeout) throws Exception { String status = null;/*from www . ja v a 2s . c o m*/ int queryResultInstanceId = 0; log.debug("in testSend"); QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); ServiceLocator serviceLocator = ServiceLocator.getInstance(); /* QueueConnection conn = serviceLocator.getQueueConnectionFactory( QUEUE_CONN_FACTORY_NAME).createQueueConnection(); Queue sendQueue = serviceLocator.getQueue(SMALL_QUEUE_NAME); Queue responseQueue = serviceLocator.getQueue(RESPONSE_QUEUE_NAME); QueueSession session = conn.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); String id = sessionId; String selector = "JMSCorrelationID='" + id + "'"; QueueSender sender = session.createSender(sendQueue); MapMessage mapMsg = session.createMapMessage(); mapMsg.setJMSCorrelationID(id); mapMsg.setJMSReplyTo(responseQueue); mapMsg.setString(XML_REQUEST_PARAM, xmlRequest); mapMsg.setString(QUERY_MASTER_GENERATED_SQL_PARAM, generatedSql); mapMsg.setString(QUERY_INSTANCE_ID_PARAM, queryInstanceId); mapMsg.setString(QUERY_PATIENT_SET_ID_PARAM, patientSetId); mapMsg.setString(DS_LOOKUP_DOMAIN_ID, domainId); mapMsg.setString(DS_LOOKUP_PROJECT_ID, projectId); mapMsg.setString(DS_LOOKUP_OWNER_ID, ownerId); sender.send(mapMsg); QueueConnection conn1 = serviceLocator.getQueueConnectionFactory( QUEUE_CONN_FACTORY_NAME).createQueueConnection(); conn1.start(); QueueSession recvSession = conn1.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); QueueReceiver rcvr = recvSession .createReceiver(responseQueue, selector); MapMessage receivedMsg = (MapMessage) rcvr.receive(timeout); if (receivedMsg == null) { status = "RUNNING"; log.info("STATUS IS RUNNING " + status); } else { String responseObj = (String) receivedMsg.getString("para1"); status = (String) receivedMsg .getString(QueryManagerBeanUtil.QUERY_STATUS_PARAM); log.debug("Got back response from executor " + responseObj); if (status != null && status.indexOf("LOCKEDOUT") > -1) { ; } else { status = "DONE"; } queryResultInstanceId = receivedMsg .getInt(QT_QUERY_RESULT_INSTANCE_ID_PARAM); log.info("RESULT INSTANCE ID " + queryResultInstanceId); } */ //TODO mm bypass JMS and call directly long waitTime = getTimeout(xmlRequest); ExecRunnable exec = new ExecRunnable(); exec.execute(generatedSql, queryInstanceId, patientSetId, xmlRequest, domainId, projectId, ownerId); Thread t = new Thread(exec); synchronized (t) { t.start(); try { //if (waitTime > 0) { // t.wait(waitTime); //} else { // t.wait(); //} long startTime = System.currentTimeMillis(); long deltaTime = -1; while ((exec.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { if (waitTime > 0) { t.wait(waitTime - deltaTime); deltaTime = System.currentTimeMillis() - startTime; } else { t.wait(); } } if (exec.isJobCompleteFlag() == false) { String timeOuterror = "Result waittime millisecond <result_waittime_ms> :" + waitTime + " elapsed, setting to next queue"; log.debug(timeOuterror); DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper(domainId, projectId, ownerId); IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); SetFinderDAOFactory sfDAOFactory = daoFactory.getSetFinderDAOFactory(); //DataSourceLookup dsLookup = sfDAOFactory.getDataSourceLookup(); // check if the status is cancelled IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); QtQueryInstance queryInstance = queryInstanceDao.getQueryInstanceByInstanceId(queryInstanceId); queryInstance.setBatchMode(MEDIUM_QUEUE); //queryInstance.setEndDate(new Date(System // .currentTimeMillis())); queryInstanceDao.update(queryInstance, false); log.debug("Set to MEDIUM Queue"); Map returnMap = new HashMap(); returnMap.put(QUERY_STATUS_PARAM, "RUNNING"); int id = Integer.parseInt(queryInstanceId); returnMap.put(QT_QUERY_RESULT_INSTANCE_ID_PARAM, id); return returnMap; //throw new Exception("Timed Out, setting to MEDIUM Queue"); } } catch (InterruptedException e) { log.error("Error in thread: " + e.getMessage()); e.printStackTrace(); throw new I2B2Exception("Thread error while running CRC job ", e); } finally { t.interrupt(); //exec = null; t = null; } } // closeAll(sender, null, conn, session); // closeAll(null, rcvr, conn1, recvSession); // closeAllTopic(rcvr,conn1,recvSession); //MM // Map returnMap = new HashMap(); // returnMap.put(QUERY_STATUS_PARAM, status); // returnMap.put(QT_QUERY_RESULT_INSTANCE_ID_PARAM, queryResultInstanceId); // return returnMap; return exec.getResult(); }
From source file:edu.harvard.i2b2.workplace.ws.WorkplaceService.java
private OMElement execute(RequestHandler handler, long waitTime) throws I2B2Exception { //do workplace processing inside thread, so that // service could send back message with timeout error. log.debug("In execute"); OMElement returnElement = null;//from ww w .java 2 s .c o m String unknownErrorMessage = "Error message delivered from the remote server \n" + "You may wish to retry your last action"; ExecutorRunnable er = new ExecutorRunnable(); er.setRequestHandler(handler); Thread t = new Thread(er); String workplaceDataResponse = null; synchronized (t) { t.start(); // try { // if (waitTime > 0) { // t.wait(waitTime); // } else { // t.wait(); // } try { long startTime = System.currentTimeMillis(); long deltaTime = -1; while ((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { if (waitTime > 0) { t.wait(waitTime - deltaTime); deltaTime = System.currentTimeMillis() - startTime; } else { t.wait(); } } workplaceDataResponse = er.getOutputString(); if (workplaceDataResponse == null) { if (er.getJobException() != null) { log.error("er.jobException is " + er.getJobException().getMessage()); log.info("waitTime is " + waitTime); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); } else if (er.isJobCompleteFlag() == false) { //<result_waittime_ms>5000</result_waittime_ms> String timeOuterror = "Remote server timed out \n" + "Result waittime = " + waitTime + " ms elapsed,\nPlease try again"; log.error(timeOuterror); log.debug("workplace waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); } else { log.error("workplace data response is null"); log.info("waitTime is " + waitTime); log.debug("workplace waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); workplaceDataResponse = MessageFactory.convertToXMLString(responseMsgType); } } } catch (InterruptedException e) { log.error(e.getMessage()); throw new I2B2Exception("Thread error while running Workplace job "); } finally { t.interrupt(); er = null; t = null; } } returnElement = MessageFactory.createResponseOMElementFromString(workplaceDataResponse); return returnElement; }
From source file:edu.harvard.i2b2.ontology.ws.OntologyService.java
private OMElement execute(RequestHandler handler, long waitTime) throws I2B2Exception { // do Ontology query processing inside thread, so that // service could sends back message with timeout error. OMElement returnElement = null;// ww w . j av a 2 s. com String unknownErrorMessage = "Error message delivered from the remote server \n" + "You may wish to retry your last action"; ExecutorRunnable er = new ExecutorRunnable(); er.setRequestHandler(handler); Thread t = new Thread(er); String ontologyDataResponse = null; synchronized (t) { t.start(); // try { // if (waitTime > 0) { // t.wait(waitTime); // } else { // t.wait(); // } try { long startTime = System.currentTimeMillis(); long deltaTime = -1; while ((er.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { if (waitTime > 0) { t.wait(waitTime - deltaTime); deltaTime = System.currentTimeMillis() - startTime; } else { t.wait(); } } ontologyDataResponse = er.getOutputString(); if (ontologyDataResponse == null) { if (er.getJobException() != null) { log.error("er.jobException is " + er.getJobException().getMessage()); log.info("waitTime is " + waitTime); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); } else if (er.isJobCompleteFlag() == false) { // <result_waittime_ms>5000</result_waittime_ms> String timeOuterror = "Remote server timed out \n" + "Result waittime = " + waitTime + " ms elapsed,\nPlease try again"; log.error(timeOuterror); log.debug("ontology waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, timeOuterror); ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); } else { log.error("ontology data response is null"); log.info("waitTime is " + waitTime); log.debug("ontology waited " + deltaTime + "ms for " + er.getRequestHandler().getClass().getName()); ResponseMessageType responseMsgType = MessageFactory.doBuildErrorResponse(null, unknownErrorMessage); ontologyDataResponse = MessageFactory.convertToXMLString(responseMsgType); } } } catch (InterruptedException e) { log.error(e.getMessage()); throw new I2B2Exception("Thread error while running Ontology job "); } finally { t.interrupt(); er = null; t = null; } } returnElement = MessageFactory.createResponseOMElementFromString(ontologyDataResponse); return returnElement; }
From source file:com.clican.pluto.dataprocess.engine.processes.TimerProcessor.java
public void process(final ProcessorContext context) throws DataProcessException { String id = UUID.randomUUID().toString(); Date start = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); Date end = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd"); final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); final List<Throwable> exceptionList = new ArrayList<Throwable>(); final Thread currentThread = Thread.currentThread(); try {/*from w ww . j a va 2 s . com*/ start = sdf2.parse(sdf1.format(start) + " " + startTime.trim()); end = sdf2.parse(sdf1.format(end) + " " + endTime.trim()); ScheduledTask task = new ScheduledTask(new Runnable() { public void run() { log.debug("timerProcessor?,?" + sdf2.format(new Date())); try { for (DataProcessor timerProcessor : timerProcessors) { if (stepCommit) { dataProcessTransaction.doInCommit(timerProcessor, context); } else { timerProcessor.beforeProcess(context); timerProcessor.process(context); timerProcessor.afterProcess(context); } } } catch (InterruptedException e) { log.error("Timer", e); exceptionList.add(e); synchronized (currentThread) { currentThread.notify(); } } catch (Throwable e) { log.error("Timer", e); exceptionList.add(e); } log.debug("timerProcessor?,?" + sdf2.format(new Date())); } }, id, cronExpression, start, end, concurrent); long timeout = end.getTime() - new Date().getTime(); if (log.isDebugEnabled()) { log.debug("timeout=" + timeout); } long beforetime = start.getTime() - new Date().getTime(); if (beforetime > 5000) { throw new InterruptedException("???task,beforetime=[" + beforetime + "]"); } if (timeout < 0) { throw new InterruptedException("????task,timeout=[" + timeout + "]"); } else { taskScheduler.schedule(id, task); synchronized (currentThread) { currentThread.wait(timeout); } } } catch (Exception e) { throw new DataProcessException("Timer[" + this.getId() + "]", e); } try { if (exceptionList.size() != 0) { throw new DataProcessException(exceptionList.get(0)); } } catch (Exception e) { throw new DataProcessException("TimerProcessor[" + this.getId() + "]", e); } finally { taskScheduler.cancel(id); } }