/* * Initiate the snapshot by sending a Marker message to one of the Players (Player0) * Any Player could have been used to initiate the snapshot. */ private void sendInitSnapshot() { try { // Gather necessary JMS resources Context ctx = new InitialContext(); ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory"); Queue q = (Queue) ctx.lookup("jms/PITplayer0"); Connection con = cf.createConnection(); Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer writer = session.createProducer(q); /* * As part of the snapshot algorithm, players need to record * what other Players they receive markers from. * "-1" indicates to the PITplayer0 that this marker is coming from * the monitor, not another Player. */ Marker m = new Marker(-1); ObjectMessage msg = session.createObjectMessage(m); System.out.println("Initiating Snapshot"); writer.send(msg); con.close(); } catch (JMSException e) { System.out.println("JMS Exception thrown" + e); } catch (Throwable e) { System.out.println("Throwable thrown" + e); } }
@Override public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); if ("SHUTDOWN".equals(text)) { LOG.info("Got the SHUTDOWN command -> exit"); producer.send(session.createTextMessage("SHUTDOWN is being performed")); } else if ("REPORT".equals(text)) { long time = System.currentTimeMillis() - start; producer.send(session.createTextMessage("Received " + count + " in " + time + "ms")); try { Thread.sleep(500); } catch (InterruptedException e) { LOG.info("Wait for the report message to be sent was interrupted"); } count = 0; } else { if (count == 0) { start = System.currentTimeMillis(); } count++; LOG.info("Received " + count + " messages."); } } } catch (JMSException e) { LOG.error("Got an JMS Exception handling message: " + message, e); } }
private void sendTextMessage(String msg) throws Exception { try (Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer publisher = session.createProducer(queue); ) { connection.start(); TextMessage message = session.createTextMessage(msg); publisher.send(message); } }
public void sendReply(Message request, int sum) { try { MessageProducer MP = session.createProducer(null); Destination reply = request.getJMSReplyTo(); TextMessage TM = session.createTextMessage(); TM.setText("" + sum); MP.send(reply, TM); } catch (JMSException JMSE) { System.out.println("JMS Exception: " + JMSE); } }
public static void main(String[] args) throws JMSException { String uri = "failover://tcp://103.224.81.184:61616"; ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uri); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Topic topic = session.createTopic("topic1"); MessageProducer producer = session.createProducer(topic); TextMessage textMessage = session.createTextMessage("HelloWorld4"); producer.send(textMessage); connection.start(); producer.close(); session.close(); connection.close(); }
private void sendJmsMessage() { String message = "Salutation generated for MDB"; try { Connection connection = queueConnectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = (MessageProducer) session.createProducer(queue); TextMessage textMessage = session.createTextMessage(); textMessage.setText(message); messageProducer.send(textMessage); Logger.getLogger("SalutationLog") .log(Level.WARNING, "Message sent successfully", "Message sent successfully2"); } catch (JMSException e) { e.printStackTrace(); } }
/** * Send a text message given a queue or topic name and a text message. * * @param destinationName destinationName * @param messageContent messageContent */ public void sendTextMessageWithDestination( final String destinationName, final String messageContent) { if (!this.isConnected()) { throw new JmsNotConnectedException("JMS connection is down " + destinationName); } final Session session = getSession(); final MessageProducer producer = getProducer(destinationName); try { TextMessage message = session.createTextMessage(messageContent); producer.send(message); } catch (JMSException e) { throw new IllegalStateException("Unable to send message to " + destinationName, e); } }
public void invoke(T message) throws EndpointException { MessageProducer messageProducer = null; Message jmsMessage = null; try { messageProducer = session.createProducer(destination); if (message instanceof FlowEvent) { jmsMessage = this.convertToMessage(((FlowEvent) message).getPayload()); // carry the event identifier if available this.managedEventIdentifierService.setEventIdentifier( ((FlowEvent<String, ?>) message).getIdentifier(), jmsMessage); } else { jmsMessage = this.convertToMessage(message); } // pass original message to getMessageProperties to allow overridding classes to implement // custom processing // and set whatever comes back as properties on the message setMessageProperties(jmsMessage, getMessageProperties(message)); // allow programmatic overrride of properties if (customMessagePropertyProvider != null) { setMessageProperties(jmsMessage, customMessagePropertyProvider.getProperties(message)); } // publish message messageProducer.send(jmsMessage); if (logger.isDebugEnabled()) { logger.debug("Published [" + message.toString() + "]"); } } catch (JMSException e) { throw new EndpointException(e); } finally { if (messageProducer != null) { try { messageProducer.close(); messageProducer = null; } catch (JMSException e) { logger.error("Failed to close session", e); } } } }
/** * Each message will be divided into groups and create the map message * * @param producer Used for sending messages to a destination * @param session Used to produce the messages to be sent * @param messagesList List of messages to be sent */ public static void publishTextMessage( MessageProducer producer, Session session, List<String> messagesList) throws JMSException { for (String message : messagesList) { TextMessage jmsMessage = session.createTextMessage(); jmsMessage.setText(message); producer.send(jmsMessage); } }
private void sendMessage(byte[] encodedMessage) { Timer.Context sendMessageTimer = messageSendingTimer.time(); messageProducer.produce(encodedMessage); sendMessageTimer.stop(); if (log.isDebugEnabled()) { log.debug("Completed send of message: " + new String(encodedMessage)); } }
public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); ConnectionFactory cf; Destination dest; try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); cf = (ConnectionFactory) envCtx.lookup("jms/connectionFactory"); dest = (Destination) envCtx.lookup(QUEUE_NAME); } catch (NamingException e) { throw new RuntimeException(e); } Connection connection = null; try { connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(dest); TextMessage message = session.createTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); log.info("Sending message: " + message.getText()); producer.send(message); } producer.send(session.createTextMessage()); } catch (JMSException e) { throw new RuntimeException(e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } out.write("<p>Wrote " + NUM_MSGS + " to queue " + QUEUE_NAME + " followed by a blank.</p>"); out.close(); }
public void _sendOne(String topic, String msg) { Session session = null; try { session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(topic); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); TextMessage message = session.createTextMessage(JSON.toJSONString(msg)); producer.send(message); session.commit(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != session) session.close(); } catch (Throwable ignore) { } } }
@Override public void destroy() { log.debug("destroy()... " + reportStatus()); if (configuration.metricsEnabled()) { metricsReporter.stop(); } messageProducer.terminate(); super.destroy(); }
private void report() { log.debug("private void report(): called"); try { String msg = getReport(); _controller.send(createReportResponseMessage(msg)); log.debug("Sent report: " + msg); } catch (Exception e) { e.printStackTrace(System.out); } }
public static void main(String[] args) throws JMSException { String user = env("ACTIVEMQ_USER", ""); String password = env("ACTIVEMQ_PASSWORD", ""); String host = env("ACTIVEMQ_HOST", "localhost"); int port = Integer.parseInt(env("ACTIVEMQ_PORT", "61616")); String destination = arg(args, 0, "foo.bar"); int messages = 10; int size = 256; String DATA = "abcdefghijklmnopqrstuvwxyz"; String body = ""; for (int i = 0; i < size; i++) { body += DATA.charAt(i % DATA.length()); } ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( "tcp://" + host + ":" + port + "?jms.useAsyncSend=false&jms.alwaysSyncSend=true"); Connection connection = factory.createConnection(user, password); logger.info("Connection created"); connection.start(); logger.info("Connection started"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination dest = new ActiveMQQueue(destination); MessageProducer producer = session.createProducer(dest); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); for (int i = 1; i <= messages; i++) { TextMessage msg = session.createTextMessage(body); msg.setIntProperty("id", i); producer.send(msg); logger.info("Message send" + i); } producer.send(session.createTextMessage("THE.END")); connection.close(); logger.info("Connection closed"); }
public void send(ExampleCommand command, String queueName, String filter) throws JMSException, IOException { try (Session session = connection.createSession()) { Message message; if (binaryMode) { message = session.createBytesMessage(); ((BytesMessage) message).writeBytes(command.toBytes()); } else { message = session.createTextMessage(command.toXml()); } if (filter != null && !blank(filter)) { String[] parts = filter.split("\\s*=\\s*"); message.setStringProperty(parts[0], parts[1]); } try (MessageProducer p = session.createProducer(ActiveMQJMSClient.createQueue(queueName))) { p.send(message, DeliveryMode.PERSISTENT, 4, 0); } } }
public void run() throws JMSException { ConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(queueName); MessageProducer producer = session.createProducer(destination); Message message = null; for (int i = 0; i < 10; i++) { System.out.println("Creating Message " + i); message = session.createTextMessage("Hello World! " + i); producer.send(message); } if (connection != null) { connection.close(); } }
/** * Sends a command into a queue for processing * * @param queueName name of queue * @param command command to process * @param deliveryMode delivery mode: {@link javax.jms.DeliveryMode}. * @param priority priority of the message. Correct values are from 0 to 9, with higher number * denoting a higher priority. * @param timeToLive the message's lifetime (in milliseconds, where 0 is to never expire) */ public void send( String queueName, Command command, int deliveryMode, int priority, int timeToLive) { try { checkRange(deliveryMode, 1, 2, "delivery mode"); checkRange(priority, 0, 9, "priority"); if (timeToLive < 0) throw new HornetNestException("time to live cannot be negative"); Queue queue = (Queue) jmsServer.lookup("/queue/" + queueName); if (queue == null) throw new HornetNestException("Failed to find queue: " + queueName); Session session = producerConnection.createSession(); TextMessage msg = session.createTextMessage(command.toString()); msg.setStringProperty("command_class", command.getClass().getName()); MessageProducer p = session.createProducer(queue); p.send(msg, deliveryMode, priority, timeToLive); } catch (HornetNestException e) { throw e; } catch (Exception e) { throw new HornetNestException("Failed to send message", e); } }
public void sendOne(String topic, String msg) { long s = System.currentTimeMillis(); Session session = null; try { session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(topic); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); TextMessage message = session.createTextMessage(msg); producer.send(message); session.commit(); logger.info("cost: {}ms {}/{}", System.currentTimeMillis() - s, topic, msg); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != session) session.close(); } catch (Throwable ignore) { } } }
public boolean send(@NotNull Value value, @Optional JMSQueue replyTo) throws JMSException { Message message = null; if (value.isArray()) { message = _session.createMapMessage(); ArrayValue array = (ArrayValue) value; Set<Map.Entry<Value, Value>> entrySet = array.entrySet(); for (Map.Entry<Value, Value> entry : entrySet) { if (entry.getValue() instanceof BinaryValue) { byte[] bytes = ((BinaryValue) entry.getValue()).toBytes(); ((MapMessage) message).setBytes(entry.getKey().toString(), bytes); } else { // every primitive except for bytes can be translated from a string ((MapMessage) message).setString(entry.getKey().toString(), entry.getValue().toString()); } } } else if (value instanceof BinaryValue) { message = _session.createBytesMessage(); byte[] bytes = ((BinaryValue) value).toBytes(); ((BytesMessage) message).writeBytes(bytes); } else if (value.isLongConvertible()) { message = _session.createStreamMessage(); ((StreamMessage) message).writeLong(value.toLong()); } else if (value.isDoubleConvertible()) { message = _session.createStreamMessage(); ((StreamMessage) message).writeDouble(value.toDouble()); } else if (value.toJavaObject() instanceof String) { message = _session.createTextMessage(); ((TextMessage) message).setText(value.toString()); } else if (value.toJavaObject() instanceof Serializable) { message = _session.createObjectMessage(); ((ObjectMessage) message).setObject((Serializable) value.toJavaObject()); } else { return false; } if (replyTo != null) message.setJMSReplyTo(replyTo._destination); _producer.send(message); return true; }
public static void publish(String dest, Serializable object, String contentType, String tag) throws Exception { Connection conn = connectionFactory.createConnection(); try { Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = createDestination(dest); MessageProducer producer = session.createProducer(destination); ObjectMessage message = session.createObjectMessage(); if (contentType != null) { message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, contentType); } if (tag != null) { message.setStringProperty("MyTag", tag); } message.setObject(object); producer.send(message); } finally { conn.close(); } }
public static void main(String[] args) throws Exception { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://localhost:61616"); QueueConnection queueConnection = connectionFactory.createQueueConnection(); QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = queueSession.createQueue("test-queue"); MessageProducer producer = queueSession.createProducer(queue); queueConnection.start(); TextMessage textMessage = queueSession.createTextMessage("Current time: " + System.currentTimeMillis()); producer.send(textMessage); log.info("Message sent at {}", System.currentTimeMillis()); producer.close(); queueSession.close(); queueConnection.close(); }
public static void main(String[] args) throws JMSException { String user = env("ACTIVEMQ_USER", "admin"); String password = env("ACTIVEMQ_PASSWORD", "password"); String host = env("ACTIVEMQ_HOST", "localhost"); int port = Integer.parseInt(env("ACTIVEMQ_PORT", "61616")); String destination = arg(args, 0, "event"); int messages = 10000; int size = 256; String DATA = "abcdefghijklmnopqrstuvwxyz"; String body = ""; for (int i = 0; i < size; i++) { body += DATA.charAt(i % DATA.length()); } ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + host + ":" + port); Connection connection = factory.createConnection(user, password); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination dest = new ActiveMQTopic(destination); MessageProducer producer = session.createProducer(dest); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); for (int i = 1; i <= messages; i++) { TextMessage msg = session.createTextMessage(body); msg.setIntProperty("id", i); producer.send(msg); if ((i % 1000) == 0) { System.out.println(String.format("Sent %d messages", i)); } } producer.send(session.createTextMessage("SHUTDOWN")); connection.close(); }
// envoyer un messsage à l'ESB public void ecrireMessage(String messageXML) throws JMSException, NamingException { // BasicConfigurator.configure(); // Obtention de connexion JMS e partir du serveur ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start(); try { // Creation de session (Messages JMS sont envoyes et recus en utilisant une session) Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Destination de la file Destination destination = session.createQueue(subject); // MessageProducer est utilise pour l'envoi de messages MessageProducer producer = session.createProducer(destination); // le message transferer TextMessage message = session.createTextMessage(messageXML); // Transfert de message vers la file ( L'ESB) producer.send(message); // System.out.println("message envoye : " + message.getText() + ""); } finally { connection.close(); } }
// Sends a message using the exchange name over qpid private void sendMessage(String message, String exchangeName) { TextMessage textMessage; properties.setProperty("topic" + "." + "cow", exchangeName); try { context = new InitialContext(properties); Destination destination = (Destination) context.lookup("cow"); messageProducer = session.createProducer(destination); textMessage = session.createTextMessage(message); messageProducer.send(textMessage); } catch (Exception e) { log.debug(e.getMessage()); initialized = false; } }
/** * Each message will be divided into groups and create the map message * * @param producer Used for sending messages to a destination * @param session Used to produce the messages to be sent * @param messagesList List of messages to be sent individual message event data should be in * "attributeName(attributeType):attributeValue" format */ public static void publishMapMessage( MessageProducer producer, Session session, List<String> messagesList) throws IOException, JMSException { String regexPattern = "(.*)\\((.*)\\):(.*)"; Pattern pattern = Pattern.compile(regexPattern); for (String message : messagesList) { MapMessage mapMessage = session.createMapMessage(); for (String line : message.split("\\n")) { if (line != null && !line.equalsIgnoreCase("")) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { mapMessage.setObject( matcher.group(1), parseAttributeValue(matcher.group(2), matcher.group(3))); } } } producer.send(mapMessage); } }
@Override public boolean offer(T event) throws FalconException { Session session; try { session = getSession(); TextMessage msg = session.createTextMessage(event.toString()); msg.setLongProperty( ScheduledMessage.AMQ_SCHEDULED_DELAY, event.getDelay(TimeUnit.MILLISECONDS)); msg.setStringProperty("TYPE", event.getType().name()); producer.send(msg); LOG.debug( "Enqueued Message: {} with delay {} milli sec", event.toString(), event.getDelay(TimeUnit.MILLISECONDS)); return true; } catch (Exception e) { LOG.error("Unable to offer event: {} to ActiveMQ", event, e); throw new FalconException("Unable to offer event:" + event + " to ActiveMQ", e); } }
public static void main(String... args) throws Exception { ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; MessageProducer producer = null; MessageConsumer consumer = null; Destination destination = null; TextMessage message = null; Context context = null; try { // Set up the context for the JNDI lookup final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL)); env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME)); env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD)); context = new InitialContext(env); // Perform the JNDI lookups String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY); log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\""); connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString); log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI"); String destinationString = System.getProperty("destination", DEFAULT_DESTINATION); log.info("Attempting to acquire destination \"" + destinationString + "\""); destination = (Destination) context.lookup(destinationString); log.info("Found destination \"" + destinationString + "\" in JNDI"); // Create the JMS connection, session, producer, and consumer connection = connectionFactory.createConnection( System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD)); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(destination); consumer = session.createConsumer(destination); connection.start(); int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT)); String content = System.getProperty("message.content", DEFAULT_MESSAGE); log.info("Sending " + count + " messages with content: " + content); // Send the specified number of messages for (int i = 0; i < count; i++) { message = session.createTextMessage(content); producer.send(message); } // Then receive the same number of messages that were sent for (int i = 0; i < count; i++) { message = (TextMessage) consumer.receive(5000); log.info("Received message with content " + message.getText()); } } catch (Exception exception) { log.severe(exception.getMessage()); throw exception; } finally { if (context != null) { context.close(); } // closing the connection takes care of the session, producer, and consumer if (connection != null) { connection.close(); } } }
public static void main(String[] args) { Connection connection = null; try { Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME); Destination destination = (Destination) context.lookup(DESTINATION_NAME); Destination controlDestination = (Destination) context.lookup(CONTROL_DESTINATION_NAME); connection = factory.createConnection(); // create a session for the control producer Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageProducer controlProducer = session.createProducer(controlDestination); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(new JmsMessageListener(session, controlProducer)); // Must have a separate session or connection for the sync MessageConsumer // per JMS spec you cannot have sync and async message consumers on the same // session Session controlSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageConsumer controlConsumer = controlSession.createConsumer(controlDestination); // calling start after the listeners have been registered connection.start(); LOG.info("Start control message consumer"); int i = 1; while (true) { // sync receive for message consumer Message message = controlConsumer.receive(MESSAGE_TIMEOUT_MILLISECONDS); if (message != null) { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); LOG.info("Got " + (i++) + ". message: " + text); if (text.startsWith("SHUTDOWN")) { break; } } } } controlConsumer.close(); controlSession.close(); consumer.close(); controlProducer.close(); session.close(); } catch (Exception e) { LOG.error(e); } finally { // got to clean up the connections and other resources! if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error(e); } } } }
@Test public void testCloseWhenHunk() throws Exception { ActiveMQConnectionFactory connectionFactory1 = new ActiveMQConnectionFactory(); connectionFactory1.setBrokerURL( "vm://localhost?brokerConfig=xbean:embedded-activemq-config.xml"); connectionFactory1.setUseAsyncSend(true); connectionFactory1.setWatchTopicAdvisories(false); connectionFactory1.setOptimizeAcknowledge(true); connectionFactory1.setAlwaysSessionAsync(false); // start up the embedded broker which is running TCP on non-standard port connectionFactory1.createConnection().start(); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); connectionFactory.setBrokerURL("tcp://localhost:61666"); // TINY QUEUE is flow controlled after 1024 bytes final ActiveMQDestination destination = ActiveMQDestination.createDestination("queue://TINY_QUEUE", (byte) 0xff); Connection connection = connectionFactory.createConnection(); connection.start(); final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageProducer producer = session.createProducer(destination); producer.setTimeToLive(0); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); final AtomicReference<Exception> publishException = new AtomicReference<Exception>(null); final AtomicReference<Exception> closeException = new AtomicReference<Exception>(null); final AtomicLong lastLoop = new AtomicLong(System.currentTimeMillis() + 100); Thread pubThread = new Thread( new Runnable() { @Override public void run() { try { byte[] data = new byte[1000]; new Random(0xdeadbeef).nextBytes(data); for (int i = 0; i < 10000; i++) { lastLoop.set(System.currentTimeMillis()); ObjectMessage objMsg = session.createObjectMessage(); objMsg.setObject(data); producer.send(destination, objMsg); } } catch (Exception e) { publishException.set(e); } } }, "PublishingThread"); pubThread.start(); // wait for publisher to deadlock while (System.currentTimeMillis() - lastLoop.get() < 1000) { Thread.sleep(100); } System.out.println("Publisher deadlock detected."); Thread closeThread = new Thread( new Runnable() { @Override public void run() { try { System.out.println("Attempting close.."); producer.close(); } catch (Exception e) { closeException.set(e); } } }, "ClosingThread"); closeThread.start(); try { closeThread.join(10000); } catch (InterruptedException ie) { assertFalse("Closing thread didn't complete in 10 seconds", true); } try { pubThread.join(10000); } catch (InterruptedException ie) { assertFalse("Publishing thread didn't complete in 10 seconds", true); } assertNull(closeException.get()); assertNotNull(publishException.get()); }