这个JAX-WS客户端调用是否线程安全?

34

由于初始化WS客户端服务和端口需要很长时间,我希望在启动时只初始化一次并重复使用相同的端口实例。初始化过程看起来会是这样:

private static RequestContext requestContext = null;

static
{
    MyService service = new MyService(); 
    MyPort myPort = service.getMyServicePort(); 

    Map<String, Object> requestContextMap = ((BindingProvider) myPort).getRequestContext();
    requestContextMap = ((BindingProvider)myPort).getRequestContext(); 
    requestContextMap.put(BindingProvider.USERNAME_PROPERTY, uName); 
    requestContextMap.put(BindingProvider.PASSWORD_PROPERTY, pWord); 

    rc = new RequestContext();
    rc.setApplication("test");
    rc.setUserId("test");
}

我的类中某处的调用:

myPort.someFunctionCall(requestContext, "someValue");
我的问题是:这个调用会线程安全吗?

3
已经在这里回答了:https://dev59.com/r2855IYBdhLWcg3wXTAI - kyiu
嗨KHY,感谢你的快速回复。我看到这个帖子了。我的问题是,我缺乏任何(官方)声明哪些是线程安全的,哪些不是(服务/端口等)。我的用例也不同于其他线程。Jonny - user871611
1
这是我在CXF网站上找到的答案:https://cwiki.apache.org/CXF/faq.html#FAQ-AreJAXWSclientproxiesthreadsafe%253F - kyiu
嗨KHY,这似乎回答了我的问题。非常感谢。 - user871611
很高兴你觉得有帮助。那我就把之前的评论复制成答案,这样问题就可以关闭了。 - kyiu
4个回答

39
根据 CXF FAQ 的说法:

JAX-WS客户端代理是否线程安全?

JAX-WS官方答案:否。 根据JAX-WS规范,客户端代理是非线程安全的。 为编写可移植代码,您应将其视为非线程安全的,并同步访问或使用一组实例等。

CXF答案:CXF代理针对许多用例是线程安全的。异常情况包括:

  • 使用 ((BindingProvider)proxy).getRequestContext() - 根据JAX-WS规范, 请求上下文是每个实例专用的。因此,在其中设置任何内容都将影响其他线程的请求。 使用CXF,您可以执行以下操作:

    ((BindingProvider)proxy).getRequestContext().put("thread.local.request.context","true");
    

    将来对getRequestContext()的调用将使用线程本地的请求上下文。这允许请求上下文在多个线程间是安全的(注意:在CXF中,响应上下文始终是线程本地的)。

  • 关于conduit的设置 - 如果您使用代码或配置直接操作conduit(例如设置TLS设置或类似项),那么这些设置不是线程安全的。 Conduit是每个实例的,因此这些设置是共享的。另外,如果您使用FailoverFeature和LoadBalanceFeatures,则conduit会动态替换。因此,在设置线程上使用之前,conduit上设置的设置可能会丢失。

  • 会话支持 - 如果您打开会话支持(请参阅jaxws规范),则会话cookie将存储在conduit中。因此,它将按照上述conduit设置规则进行共享。
  • WS-Security tokens - 如果使用WS-SecureConversation或WS-Trust,则检索到的令牌将缓存在Endpoint / Proxy中,以避免获取令牌时进行额外(且昂贵)的调用。因此,多个线程将共享该令牌。如果每个线程具有不同的安全凭据或要求,则需要使用单独的代理实例。

针对conduit问题,您可以安装一个新的ConduitSelector,该选择器使用线程本地或类似工具。但这有点复杂。

对于大多数“简单”的用例,您可以在多个线程上使用CXF代理。以上概述了其他情况的解决方法。


3
正如您在上面的回答中所看到的,JAX-WS客户端代理不是线程安全的,因此我想与其他人分享我的实现方法,以缓存客户端代理。我曾经遇到同样的问题,并决定创建一个Spring bean来缓存JAX-WS客户端代理。您可以查看更多详细信息:http://programtalk.com/java/using-spring-and-scheduler-to-store/
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

/**
 * This keeps the cache of MAX_CUNCURRENT_THREADS number of
 * appConnections and tries to shares them equally amongst the threads. All the
 * connections are created right at the start and if an error occurs then the
 * cache is created again.
 *
 */
/*
 *
 * Are JAX-WS client proxies thread safe? <br/> According to the JAX-WS spec,
 * the client proxies are NOT thread safe. To write portable code, you should
 * treat them as non-thread safe and synchronize access or use a pool of
 * instances or similar.
 *
 */
@Component
public class AppConnectionCache {

 private static final Logger logger = org.apache.logging.log4j.LogManager.getLogger(AppConnectionCache.class);

 private final Map<Integer, MyService> connectionCache = new ConcurrentHashMap<Integer, MyService>();

 private int cachedConnectionId = 1;

 private static final int MAX_CUNCURRENT_THREADS = 20;

 private ScheduledExecutorService scheduler;

 private boolean forceRecaching = true; // first time cache

 @PostConstruct
 public void init() {
  logger.info("starting appConnectionCache");
  logger.info("start caching connections"); ;;
  BasicThreadFactory factory = new BasicThreadFactory.Builder()
    .namingPattern("appconnectioncache-scheduler-thread-%d").build();
  scheduler = Executors.newScheduledThreadPool(1, factory);

  scheduler.scheduleAtFixedRate(new Runnable() {
   @Override
   public void run() {
    initializeCache();
   }

  }, 0, 10, TimeUnit.MINUTES);

 }

 public void destroy() {
  scheduler.shutdownNow();
 }

 private void initializeCache() {
  if (!forceRecaching) {
   return;
  }
  try {
   loadCache();
   forceRecaching = false; // this flag is used for initializing
   logger.info("connections creation finished successfully!");
  } catch (MyAppException e) {
   logger.error("error while initializing the cache");
  }
 }

 private void loadCache() throws MyAppException {
  logger.info("create and cache appservice connections");
  for (int i = 0; i < MAX_CUNCURRENT_THREADS; i++) {
   tryConnect(i, true);
  }
 }

 public MyPort getMyPort() throws MyAppException {
  if (cachedConnectionId++ == MAX_CUNCURRENT_THREADS) {
   cachedConnectionId = 1;
  }
  return tryConnect(cachedConnectionId, forceRecaching);
 }

 private MyPort tryConnect(int threadNum, boolean forceConnect) throws MyAppException {
  boolean connect = true;
  int tryNum = 0;
  MyPort app = null;
  while (connect && !Thread.currentThread().isInterrupted()) {
   try {
    app = doConnect(threadNum, forceConnect);
    connect = false;
   } catch (Exception e) {
    tryNum = tryReconnect(tryNum, e);
   }
  }
  return app;
 }

 private int tryReconnect(int tryNum, Exception e) throws MyAppException {
  logger.warn(Thread.currentThread().getName() + " appservice service not available! : " + e);
  // try 10 times, if
  if (tryNum++ < 10) {
   try {
    logger.warn(Thread.currentThread().getName() + " wait 1 second");
    Thread.sleep(1000);
   } catch (InterruptedException f) {
    // restore interrupt
    Thread.currentThread().interrupt();
   }
  } else {
   logger.warn(" appservice could not connect, number of times tried: " + (tryNum - 1));
   this.forceRecaching = true;
   throw new MyAppException(e);
  }
  logger.info(" try reconnect number: " + tryNum);
  return tryNum;
 }

 private MyPort doConnect(int threadNum, boolean forceConnect) throws InterruptedException {
  MyService service = connectionCache.get(threadNum);
  if (service == null || forceConnect) {
   logger.info("app service connects : " + (threadNum + 1) );
   service = new MyService();
   connectionCache.put(threadNum, service);
   logger.info("connect done for " + (threadNum + 1));
  }
  return service.getAppPort();
 }
}

3
一般来说,不行。
根据CXF FAQ http://cxf.apache.org/faq.html#FAQ-AreJAX-WSclientproxiesthreadsafe?

JAX-WS官方回答: 不行。根据JAX-WS规范,客户端代理是不线程安全的。为了编写可移植的代码,您应该将它们视为非线程安全的,并同步访问或使用实例池或类似方法。

CXF回答: CXF代理对于许多用例是线程安全的。

有关异常列表,请参见FAQ。

1
一般的解决方案是使用多个客户端对象池,然后使用充当外观的代理。
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

class ServiceObjectPool<T> extends GenericObjectPool<T> {
        public ServiceObjectPool(java.util.function.Supplier<T> factory) {
            super(new BasePooledObjectFactory<T>() {
                @Override
                public T create() throws Exception {
                    return factory.get();
                }
            @Override
            public PooledObject<T> wrap(T obj) {
                return new DefaultPooledObject<>(obj);
            }
        });
    }

    public static class PooledServiceProxy<T> implements InvocationHandler {
        private ServiceObjectPool<T> pool;

        public PooledServiceProxy(ServiceObjectPool<T> pool) {
            this.pool = pool;
        }


        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            T t = null;
            try {
                t = this.pool.borrowObject();
                return method.invoke(t, args);
            } finally {
                if (t != null)
                    this.pool.returnObject(t);
            }
        }
    }

    @SuppressWarnings("unchecked")
    public T getProxy(Class<? super T> interfaceType) {
        PooledServiceProxy<T> handler = new PooledServiceProxy<>(this);
        return (T) Proxy.newProxyInstance(interfaceType.getClassLoader(),
                                          new Class<?>[]{interfaceType}, handler);
    }
}

使用代理的方法如下:
ServiceObjectPool<SomeNonThreadSafeService> servicePool = new ServiceObjectPool<>(createSomeNonThreadSafeService);
nowSafeService = servicePool .getProxy(SomeNonThreadSafeService.class);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接