JMS超时处理方案2

/**
* set client id
* @param conn jms connection
* @param timeout timeout
* @param unit time unit
* @return Boolean true or false
* @throws LogCollectionException LogCollectionException
* @throws IOException IOException
*/
public static Boolean setClientId(final QueueConnection conn, long timeout,
TimeUnit unit) throws LogCollectionException, IOException
{
final BlockingQueue<Object> mailbox = new ArrayBlockingQueue<Object>(1);
ExecutorService executor = Executors.newSingleThreadExecutor(new DaemonThreadFactory());
executor.submit(new Runnable()
{
public void run()
{
try
{

conn.setClientID(UUID.randomUUID().toString());
mailbox.offer(Boolean.TRUE);
}
catch (JMSException e)
{
mailbox.offer(e);
}
}
});
Object result;
try
{
result = mailbox.poll(timeout, unit);
if (result == null)
{
if (!mailbox.offer("time out"))
{
result = mailbox.take();
}
}
}
catch (InterruptedException e)
{
closeConn(conn);
throw initCause(new InterruptedIOException(e.getMessage()), e);
}
finally
{
executor.shutdownNow();
}
if (result == null)
{
closeConn(conn);
throw new SocketTimeoutException("Connect timed out");
}
if (result instanceof Boolean)
{
return (Boolean)result;
}
if (result instanceof JMSException)
{
closeConn(conn);
throw new LogCollectionException("IO Execption",
(JMSException)result);
}
throw new IOException("Unknown reason!");
}

/**
* wrapper cause.
* @param <T> throwable
* @param wrapper cause wrapper
* @param wrapped throwable
* @return
*/
private static <T extends Throwable> T initCause(T wrapper,
Throwable wrapped)
{
wrapper.initCause(wrapped);
return wrapper;
}

/**
* close connection
*
* @param conn jms connection
*/
private static void closeConn(Connection conn)
{
if (conn != null)
{
try
{
conn.close();
}
catch (JMSException e)
{
LOGGER.error(e.toString(), e);
}
}
}
}

/**
* 内部私有类
* 线程工厂,ExecutorService调用newThread方法自动创建线程。
* @version [版本号,YYYY-MM-DD]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
class DaemonThreadFactory implements ThreadFactory
{
public Thread newThread(Runnable r)
{
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setDaemon(true);
return t;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值