Skip to main content

Re: JAX WS clients

6 replies [Last post]
Anonymous

Regarding the thread safety this is what i found on an oracle forum :

https://forums.oracle.com/forums/thread.jspa?threadID=2260797

"
mac24nz wrote:
Do I need to be concerned about the calls to getPort()? do I need a Port instance for each thread, or is 1 instance of getPort sufficient for all threads?

If you call getPort() in the method that needs it, you will have no threading issues. But since the port must have no state, a single port object should be able to be shared by multiple threads without collision in the same way a Stateless EJB is thread safe.

Let me put it in another way: I've never had issues with it either way, if you want to rely on what I say to be true.
"

So is the port thread safe ? I start to be confused :))

Regards...

On 03 Jul 2012, at 17:23, Andreas Loew wrote:

> Hi Cristian,
>
> Am 03.07.2012 15:55, schrieb Cristian Chiovari:
>>
>> Well I guess understand and sorry for prolonging this discussion:
>>
>> public final class ThreadContext {
>>
>> private static ThreadLocal threadLocal = new ThreadLocal();
>>
>> private Port1 port1;
>> private Port2 port2;
>> ....
>> private Port3 port3;
>> private ThreadContext() {
>> super();
>> }
>> public static ThreadContext getInstance() {
>> ThreadContext result;
>> result = (ThreadContext) threadLocal.get();
>> if (result == null) {
>> result = new ThreadContext();
>> threadLocal.set(result);
>> }
>> return result;
>> }
>>
>> .............
>> setter and getter for ports
>> ............
>> public static void unset() {
>> threadLocal.remove();
>> }
>> }
>>
>> public class ThreadContextInitFilter implements Filter{
>>
>> public void init(FilterConfig filterConfig) throws ServletException {
>> }
>> public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain chain) throws IOException, ServletException {
>> ThreadContext threadContext = ThreadContext.getInstance();
>> // get the port from a static service !
>> threadContext.setPort1 (port1);
>> chain.doFilter(servletRequest, servletResponse);
>> }
>> }
>> }
> Yes indeed - the ThreadContext pattern is what I was targetting at, although I am somewhat wondering why - when we are looking at the web app as WS client use case - you should like to complicate things and use a servlet Filter?
>
> At least as long as you call into synchronous web service methods on the remote end, you can theoretically do the whole WS client handling within a single client (Servlet) class, which
> creates the private static Service instance in a static constructor or during the HttpServlet init() method (which is guaranteed to be called in a thread-safe manner)
> only use local method variables (no instance variables!) to work with the ThreadContext to get and dispose/remove your Port instance during your request processing method (doGet() or doPost(), as you like) - if you do so, your code is also perfectly thread-safe
> if you do a more complex scenario and run into the need to store some state between methods, delegate from the servlet to a simple POJO class which then implements the WS client, and create and destruct a new instance of this light-weight POJO for every request using CDI bean class scope @Dependent - like the Spring scope="prototype" pattern would do for a Spring bean in case you are more familiar with that
> the POJO then does not need to be thread-safe any more, but should still use a singleton private static Service instance and get/dispose the Port from the ThreadContext
>> There are some people that are against using ThreadLocal however that is another discussion.
>> http://stackoverflow.com/questions/7022245/threadlocal-safety-in-weblogi...
>> http://www.adam-bien.com/roller/abien/entry/how_to_pass_context_with
> The people stating their objections here do so out of an "ivory tower". In theory, following the letter of the Spec, the EJB container would be free to change worker threads whenever (i.e. immediately before) a new EJB method is being called into - but in practice, I have never seen any real world implementation that does so - why should it? It would run into all kinds of issues internally - guess what: The EJB container typically manages the mapping between its worker threads calling into transactional EJBs and its transaction context in the exact same way by using ThreadLocals, and nobody would have any interest in or advantage from changing this mapping at every call into a new EJB method.
>
> So yes, in the "ivory tower", using ThreadLocals within the EJB container could theoretically fail, but believe me - there is no real reason to assume that this a realistic scenario and will ever happen.
>
>> What do you think about using @WebServiceRef ?
>> http://docs.oracle.com/cd/E15051_01/wls/docs103/webserv/client.html#wp23...
> I don't really get the point of what/why you are asking - You should definitely use this to annotate the static variable within your Servlet class which is to hold the Singleton thread-safe Service object representing your target WS for the call.
>
>> Many thanks !
> As I am currently on long-term sick leave and read my e-mails right now for my personal distraction, you are more than welcome to receive some insights from me for free. ;-)
> In case you would like to receive regular Java consulting on a daily basis, you will of course need to engage Oracle Advanced Customer Services (ACS)... :-)
>
> Best regards from Germany,
>
> Andreas
>
>> On Tue, Jul 3, 2012 at 2:47 PM, Andreas Loew wrote:
>> Hi Cristian,
>>
>> Am 03.07.2012 14:22, schrieb Cristian Chiovari:
>>
>> What i have used in the past was done based on http://commons.apache.org/pool/ .So when the web app started the pool was initialized with a pre configured number of instance services. (Ports were created each time ....but as i understood they might be cached as well)
>> This is NOT AT ALL needed! You can create just one single static Service instance per WSDL: Any single Service object is fully thread-safe and can be shared by as many concurrent threads as you like. So "caching" a Service basically means making it a static property of your client class, nothing more. Therefore, this single object also needs to be initialized only once from the WSDL.
>>
>>
>> Just thinking that another solution is to use a dynamic pool for ports that can be increase when needed and decreased when there is no load
>> A dynamic pool of Port/Dispatch objects would be an "ideal" solution, but as stated before, particularly in an environment where your WS client is running from within a Java EE container and you therefore have no direct control about the number of worker threads from your WorkManager (i.e. either your HTTP session pool, EJB pool, or maybe even both depending on the call scenarios), I'd rather recommend the ThreadLocal solution: It is very simple as far as the codebase is concerned, and - from my experience - still tolerable regarding the amount of memory used (again, the Service instance is the big object, not the Port).
>>
>> This means use a lazily initialized static ThreadLocal to cache a dedicated Port object to be used from the current worker thread. Running the app for a while, successively all the threads from your WorkManager's thread pool (HTTP session pool, EJB pool) will have their thread's dedicated Port object created and cached, and these will then be reused once the same worker thread is reassigned by the container WorkManager to execute another WS client request of the same sort...
>>
>> Did I make myself clear enough now? Unfortunately, I don't have any code sample at hand which is simple enough to post it here...
>>
>> HTH & BR,
>>
>> Andreas
>

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
al130959
Offline
Joined: 2005-09-28
Points: 0

Hi Cristian,

as I wrote in my very first reply, the thread safety of Port objects
depends on the particular JAX-WS implementation that you are using. The
JAX-WS specification itself does NOT require Port and Dispatch objects
to be thread-safe.

So not every statement in the forums must be 100% true:

While it might be possible that WLS JAX-WS Ports are thread-safe (not
certain at all, as I haven't used WLS JAX-WS yet - although WLS JAX-WS
is based on Metro...), and while I am almost 100% certain that CXF
JAX-WS Ports are thread-safe, Metro's Port objects definitely are NOT
thread-safe:

You get access to the BindingProvider object through the port, which in
Metro is an unsynchronized HashMap (at least, it was in Metro 1.4 when I
last checked, but I believe it still is).

As you can e.g. do the following:

| Map context= ((BindingProvider) port).getRequestContext();
Map> headers= new HashMap>();
headers.put("Username", Collections.singletonList("yourusername"));
headers.put("Password", Collections.singletonList("yourpassword"));
|

to set a per-request username and password, and this might be different
username/password combos for different requests, or, to give another
sample, access the response's HTTP headers:

headers = (Map>) ((BindingProvider) port).getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS);

I hope it becomes quite clear that you better NOT share the port between
several threads - at least not in case you are interested in any request
or response info contained in the BindingProvider map.

Hope this further clarifies it...

Best regards & have a nice weekend,

Andreas

Am 06.07.2012 19:45, schrieb Cristian Chiovari:
>
> Regarding the thread safety this is what i found on an oracle forum :
>
> https://forums.oracle.com/forums/thread.jspa?threadID=2260797
>
> "
> mac24nz wrote:
> Do I need to be concerned about the calls to getPort()? do I need a
> Port instance for each thread, or is 1 instance of getPort sufficient
> for all threads?
>
> If you call getPort() in the method that needs it, you will have no
> threading issues. But since the port must have no state, a single port
> object should be able to be shared by multiple threads without
> collision in the same way a Stateless EJB is thread safe.
>
> Let me put it in another way: I've never had issues with it either
> way, if you want to rely on what I say to be true.
>
> "
>
> So is the port thread safe ? I start to be confused :))
>
> Regards...
>
> On 03 Jul 2012, at 17:23, Andreas Loew wrote:
>
>> Hi Cristian,
>>
>> Am 03.07.2012 15:55, schrieb Cristian Chiovari:
>>> Well I guess understand and sorry for prolonging this discussion:
>>>
>>> public final class ThreadContext {
>>>
>>> private static ThreadLocal threadLocal = new
>>> ThreadLocal();
>>>
>>> private Port1 port1;
>>> private Port2 port2;
>>> ....
>>> private Port3 port3;
>>> private ThreadContext() {
>>> super();
>>> }
>>> public static ThreadContext getInstance() {
>>> ThreadContext result;
>>> result = (ThreadContext) threadLocal.get();
>>> if (result == null) {
>>> result = new ThreadContext();
>>> threadLocal.set(result);
>>> }
>>> return result;
>>> }
>>>
>>> .............
>>> setter and getter for ports
>>> ............
>>> public static void unset() {
>>> threadLocal.remove();
>>> }
>>> }
>>>
>>> public class ThreadContextInitFilter implements Filter{
>>>
>>> public void init(FilterConfig filterConfig) throws
>>> ServletException {
>>> }
>>> public void doFilter(ServletRequest servletRequest,
>>> ServletResponse servletResponse,FilterChain chain) throws
>>> IOException, ServletException {
>>> ThreadContext threadContext = ThreadContext.getInstance();
>>> // get the port from a static service !
>>> threadContext.setPort1 (port1);
>>> chain.doFilter(servletRequest, servletResponse);
>>> }
>>> }
>>> }
>> Yes indeed - the ThreadContext pattern is what I was targetting at,
>> although I am somewhat wondering why - when we are looking at the web
>> app as WS client use case - you should like to complicate things and
>> use a servlet Filter?
>>
>> At least as long as you call into synchronous web service methods on
>> the remote end, you can theoretically do the whole WS client handling
>> within a single client (Servlet) class, which
>>
>> * creates the private static Service instance in a static
>> constructor or during the HttpServlet init() method (which is
>> guaranteed to be called in a thread-safe manner)
>> * only use local method variables (no instance variables!) to work
>> with the ThreadContext to get and dispose/remove your Port
>> instance during your request processing method (doGet() or
>> doPost(), as you like) - if you do so, your code is also
>> perfectly thread-safe
>>
>> * if you do a more complex scenario and run into the need to store
>> some state between methods, delegate from the servlet to a simple
>> POJO class which then implements the WS client, and create and
>> destruct a new instance of this light-weight POJO for every
>> request using CDI bean class scope @Dependent - like the Spring
>> scope="prototype" pattern would do for a Spring bean in case you
>> are more familiar with that
>> * the POJO then does not need to be thread-safe any more, but
>> should still use a singleton private static Service instance and
>> get/dispose the Port from the ThreadContext
>>
>>> There are some people that are against using ThreadLocal however
>>> that is another discussion.
>>> http://stackoverflow.com/questions/7022245/threadlocal-safety-in-weblogi...
>>> http://www.adam-bien.com/roller/abien/entry/how_to_pass_context_with
>> The people stating their objections here do so out of an "ivory
>> tower". In *theory*, following the letter of the Spec, the EJB
>> container would be free to change worker threads whenever (i.e.
>> immediately before) a new EJB method is being called into - but in
>> practice, I have never seen any real world implementation that does
>> so - why should it? It would run into all kinds of issues internally
>> - guess what: The EJB container typically manages the mapping between
>> its worker threads calling into transactional EJBs and its
>> transaction context in the exact same way by using ThreadLocals, and
>> nobody would have any interest in or advantage from changing this
>> mapping at every call into a new EJB method.
>>
>> So yes, in the "ivory tower", using ThreadLocals within the EJB
>> container could theoretically fail, but believe me - there is no real
>> reason to assume that this a realistic scenario and will ever happen.
>>
>>> What do you think about using @WebServiceRef ?
>>> http://docs.oracle.com/cd/E15051_01/wls/docs103/webserv/client.html#wp23...
>> I don't really get the point of what/why you are asking - You should
>> definitely use this to annotate the static variable within your
>> Servlet class which is to hold the Singleton thread-safe Service
>> object representing your target WS for the call.
>>
>>> Many thanks !
>> As I am currently on long-term sick leave and read my e-mails right
>> now for my personal distraction, you are more than welcome to receive
>> some insights from me for free. ;-)
>> In case you would like to receive regular Java consulting on a daily
>> basis, you will of course need to engage Oracle Advanced Customer
>> Services (ACS)... :-)
>>
>> Best regards from Germany,
>>
>> Andreas
>>
>>> On Tue, Jul 3, 2012 at 2:47 PM, Andreas Loew
>>> > wrote:
>>>
>>> Hi Cristian,
>>>
>>> Am 03.07.2012 14:22, schrieb Cristian Chiovari:
>>>
>>> What i have used in the past was done based on
>>> http://commons.apache.org/pool/ .So when the web app started
>>> the pool was initialized with a pre configured number of
>>> instance services. (Ports were created each time ....but as
>>> i understood they might be cached as well)
>>>
>>> This is NOT AT ALL needed! You can create just one single static
>>> Service instance per WSDL: Any single Service object is fully
>>> thread-safe and can be shared by as many concurrent threads as
>>> you like. So "caching" a Service basically means making it a
>>> static property of your client class, nothing more. Therefore,
>>> this single object also needs to be initialized only once from
>>> the WSDL.
>>>
>>>
>>> Just thinking that another solution is to use a dynamic pool
>>> for ports that can be increase when needed and decreased
>>> when there is no load
>>>
>>> A dynamic pool of Port/Dispatch objects would be an "ideal"
>>> solution, but as stated before, particularly in an environment
>>> where your WS client is running from within a Java EE container
>>> and you therefore have no direct control about the number of
>>> worker threads from your WorkManager (i.e. either your HTTP
>>> session pool, EJB pool, or maybe even both depending on the call
>>> scenarios), I'd rather recommend the ThreadLocal solution: It is
>>> very simple as far as the codebase is concerned, and - from my
>>> experience - still tolerable regarding the amount of memory used
>>> (again, the Service instance is the big object, not the Port).
>>>
>>> This means use a lazily initialized static ThreadLocal to cache
>>> a dedicated Port object to be used from the current worker
>>> thread. Running the app for a while, successively all the
>>> threads from your WorkManager's thread pool (HTTP session pool,
>>> EJB pool) will have their thread's dedicated Port object created
>>> and cached, and these will then be reused once the same worker
>>> thread is reassigned by the container WorkManager to execute
>>> another WS client request of the same sort...
>>>
>>> Did I make myself clear enough now? Unfortunately, I don't have
>>> any code sample at hand which is simple enough to post it here...
>>>
>>> HTH & BR,
>>>
>>> Andreas
>>>

Anonymous

Sent from my iPad

On 07 Jul 2012, at 00:34, Andreas Loew wrote:

> Hi Cristian,
>
> as I wrote in my very first reply, the thread safety of Port objects depends on the particular JAX-WS implementation that you are using. The JAX-WS specification itself does NOT require Port and Dispatch objects to be thread-safe.
>
> So not every statement in the forums must be 100% true:

Of course i do not take for granted everything that i read on forums ....This time that asnswer came from a top poster more then 10000 posts so that is why i hesitated.....
I just wanted to understand better how ports work.

As i see now things even metro ports might be used by multiple threads .one example is if you use same user name and password for each call. There are Ws that are secured based on a group and each clent application gets its own username and pass. so in this case i do notmsee what might be the problem.

also when you use a non secured webservice and all you need is request response...there is no shared state in the port that might put in danger because multiple threads are using the port.

What i see problematic is indeed when each request has some particular info place in requestcontext....or as is specified in apache cxf faq.

Hope i understood correctly....

Cheers

Cristian

One o
F
>
> While it might be possible that WLS JAX-WS Ports are thread-safe (not certain at all, as I haven't used WLS JAX-WS yet - although WLS JAX-WS is based on Metro...), and while I am almost 100% certain that CXF JAX-WS Ports are thread-safe, Metro's Port objects definitely are NOT thread-safe:
>
> You get access to the BindingProvider object through the port, which in Metro is an unsynchronized HashMap (at least, it was in Metro 1.4 when I last checked, but I believe it still is).
>
> As you can e.g. do the following:
>
> | Map context= ((BindingProvider) port).getRequestContext();
> Map> headers= new HashMap>();
> headers.put("Username", Collections.singletonList("yourusername"));
> headers.put("Password", Collections.singletonList("yourpassword"));
> |
>
> to set a per-request username and password, and this might be different username/password combos for different requests, or, to give another sample, access the response's HTTP headers:
>
> headers = (Map>) ((BindingProvider) port).getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS);
>
> I hope it becomes quite clear that you better NOT share the port between several threads - at least not in case you are interested in any request or response info contained in the BindingProvider map.
>
> Hope this further clarifies it...
>
> Best regards & have a nice weekend,
>
> Andreas
>
>
> Am 06.07.2012 19:45, schrieb Cristian Chiovari:
>>
>> Regarding the thread safety this is what i found on an oracle forum :
>>
>> https://forums.oracle.com/forums/thread.jspa?threadID=2260797
>>
>> "
>> mac24nz wrote:
>> Do I need to be concerned about the calls to getPort()? do I need a Port instance for each thread, or is 1 instance of getPort sufficient for all threads?
>>
>> If you call getPort() in the method that needs it, you will have no threading issues. But since the port must have no state, a single port object should be able to be shared by multiple threads without collision in the same way a Stateless EJB is thread safe.
>>
>> Let me put it in another way: I've never had issues with it either way, if you want to rely on what I say to be true.
>>
>> "
>>
>> So is the port thread safe ? I start to be confused :))
>>
>> Regards...
>>
>> On 03 Jul 2012, at 17:23, Andreas Loew wrote:
>>
>>> Hi Cristian,
>>>
>>> Am 03.07.2012 15:55, schrieb Cristian Chiovari:
>>>> Well I guess understand and sorry for prolonging this discussion:
>>>>
>>>> public final class ThreadContext {
>>>>
>>>> private static ThreadLocal threadLocal = new ThreadLocal();
>>>>
>>>> private Port1 port1;
>>>> private Port2 port2;
>>>> ....
>>>> private Port3 port3;
>>>> private ThreadContext() {
>>>> super();
>>>> }
>>>> public static ThreadContext getInstance() {
>>>> ThreadContext result;
>>>> result = (ThreadContext) threadLocal.get();
>>>> if (result == null) {
>>>> result = new ThreadContext();
>>>> threadLocal.set(result);
>>>> }
>>>> return result;
>>>> }
>>>>
>>>> .............
>>>> setter and getter for ports
>>>> ............
>>>> public static void unset() {
>>>> threadLocal.remove();
>>>> }
>>>> }
>>>>
>>>> public class ThreadContextInitFilter implements Filter{
>>>>
>>>> public void init(FilterConfig filterConfig) throws ServletException {
>>>> }
>>>> public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain chain) throws IOException, ServletException {
>>>> ThreadContext threadContext = ThreadContext.getInstance();
>>>> // get the port from a static service !
>>>> threadContext.setPort1 (port1);
>>>> chain.doFilter(servletRequest, servletResponse);
>>>> }
>>>> }
>>>> }
>>> Yes indeed - the ThreadContext pattern is what I was targetting at, although I am somewhat wondering why - when we are looking at the web app as WS client use case - you should like to complicate things and use a servlet Filter?
>>>
>>> At least as long as you call into synchronous web service methods on the remote end, you can theoretically do the whole WS client handling within a single client (Servlet) class, which
>>>
>>> * creates the private static Service instance in a static
>>> constructor or during the HttpServlet init() method (which is
>>> guaranteed to be called in a thread-safe manner)
>>> * only use local method variables (no instance variables!) to work
>>> with the ThreadContext to get and dispose/remove your Port
>>> instance during your request processing method (doGet() or
>>> doPost(), as you like) - if you do so, your code is also
>>> perfectly thread-safe
>>>
>>> * if you do a more complex scenario and run into the need to store
>>> some state between methods, delegate from the servlet to a simple
>>> POJO class which then implements the WS client, and create and
>>> destruct a new instance of this light-weight POJO for every
>>> request using CDI bean class scope @Dependent - like the Spring
>>> scope="prototype" pattern would do for a Spring bean in case you
>>> are more familiar with that
>>> * the POJO then does not need to be thread-safe any more, but
>>> should still use a singleton private static Service instance and
>>> get/dispose the Port from the ThreadContext
>>>
>>>> There are some people that are against using ThreadLocal however that is another discussion.
>>>> http://stackoverflow.com/questions/7022245/threadlocal-safety-in-weblogi...
>>>> http://www.adam-bien.com/roller/abien/entry/how_to_pass_context_with
>>> The people stating their objections here do so out of an "ivory tower". In *theory*, following the letter of the Spec, the EJB container would be free to change worker threads whenever (i.e. immediately before) a new EJB method is being called into - but in practice, I have never seen any real world implementation that does so - why should it? It would run into all kinds of issues internally - guess what: The EJB container typically manages the mapping between its worker threads calling into transactional EJBs and its transaction context in the exact same way by using ThreadLocals, and nobody would have any interest in or advantage from changing this mapping at every call into a new EJB method.
>>>
>>> So yes, in the "ivory tower", using ThreadLocals within the EJB container could theoretically fail, but believe me - there is no real reason to assume that this a realistic scenario and will ever happen.
>>>
>>>> What do you think about using @WebServiceRef ?
>>>> http://docs.oracle.com/cd/E15051_01/wls/docs103/webserv/client.html#wp23...
>>> I don't really get the point of what/why you are asking - You should definitely use this to annotate the static variable within your Servlet class which is to hold the Singleton thread-safe Service object representing your target WS for the call.
>>>
>>>> Many thanks !
>>> As I am currently on long-term sick leave and read my e-mails right now for my personal distraction, you are more than welcome to receive some insights from me for free. ;-)
>>> In case you would like to receive regular Java consulting on a daily basis, you will of course need to engage Oracle Advanced Customer Services (ACS)... :-)
>>>
>>> Best regards from Germany,
>>>
>>> Andreas
>>>
>>>> On Tue, Jul 3, 2012 at 2:47 PM, Andreas Loew > wrote:
>>>>
>>>> Hi Cristian,
>>>>
>>>> Am 03.07.2012 14:22, schrieb Cristian Chiovari:
>>>>
>>>> What i have used in the past was done based on
>>>> http://commons.apache.org/pool/ .So when the web app started
>>>> the pool was initialized with a pre configured number of
>>>> instance services. (Ports were created each time ....but as
>>>> i understood they might be cached as well)
>>>>
>>>> This is NOT AT ALL needed! You can create just one single static
>>>> Service instance per WSDL: Any single Service object is fully
>>>> thread-safe and can be shared by as many concurrent threads as
>>>> you like. So "caching" a Service basically means making it a
>>>> static property of your client class, nothing more. Therefore,
>>>> this single object also needs to be initialized only once from
>>>> the WSDL.
>>>>
>>>>
>>>> Just thinking that another solution is to use a dynamic pool
>>>> for ports that can be increase when needed and decreased
>>>> when there is no load
>>>>
>>>> A dynamic pool of Port/Dispatch objects would be an "ideal"
>>>> solution, but as stated before, particularly in an environment
>>>> where your WS client is running from within a Java EE container
>>>> and you therefore have no direct control about the number of
>>>> worker threads from your WorkManager (i.e. either your HTTP
>>>> session pool, EJB pool, or maybe even both depending on the call
>>>> scenarios), I'd rather recommend the ThreadLocal solution: It is
>>>> very simple as far as the codebase is concerned, and - from my
>>>> experience - still tolerable regarding the amount of memory used
>>>> (again, the Service instance is the big object, not the Port).
>>>>
>>>> This means use a lazily initialized static ThreadLocal to cache
>>>> a dedicated Port object to be used from the current worker
>>>> thread. Running the app for a while, successively all the
>>>> threads from your WorkManager's thread pool (HTTP session pool,
>>>> EJB pool) will have their thread's dedicated Port object created
>>>> and cached, and these will then be reused once the same worker
>>>> thread is reassigned by the container WorkManager to execute
>>>> another WS client request of the same sort...
>>>>
>>>> Did I make myself clear enough now? Unfortunately, I don't have
>>>> any code sample at hand which is simple enough to post it here...
>>>>
>>>> HTH & BR,
>>>>
>>>> Andreas
>>>>
>

al130959
Offline
Joined: 2005-09-28
Points: 0

Hi Cristian, hi everybody else attempted fo follow Cristian's reasoning,

Am 07.07.2012 09:37, schrieb :
> As i see now things even metro ports might be used by multiple threads
> .one example is if you use same user name and password for each call.
> There are Ws that are secured based on a group and each clent
> application gets its own username and pass. so in this case i do
> notmsee what might be the problem. also when you use a non secured
> webservice and all you need is request response...there is no shared
> state in the port that might put in danger because multiple threads
> are using the port. What i see problematic is indeed when each request
> has some particular info place in requestcontext....or as is specified
> in apache cxf faq. Hope i understood correctly....
yes, your understanding of how it works definitely is correct now.

However, I would still like to strongly advise you (and anybody else
reading this out there) against sharing Port and/or Dispatch objects
between threads in multi-threaded JAX-WS clients.

With the proposed solution to use the ThreadLocal approach to cache one
dedicated Port/Dispatch object per thread, there is a fully spec
compliant solution which does only impose quite a low additional
overhead of complexity (and also of memory - the JAX-WS Service is the
huge object referencing the parsed WSDL contents etc.) to your code.

On the other hand, there is a huge number of disadvantages if you start
sharing the Port between threads in your code without any "security
measures":

* You leave the grounds of the spec, which clearly states Port/Dispatch
must not be expected to be thread safe.

* This basically means you introduce a hard-coded dependency on the
particular "proprietary" JAX-WS implementation you are using right now
into your code: Simply switch to another implementation (such as from
CXF and its "prorietary" thread-safety extension to Metro), and your
code might break. This is not the Java and Java EE intention of coding
against standards.

* The maintainability of your code becomes questionable at least: When
relying onto the thread-safety of a particular Port implementation, can
you indeed fully document all the assumptions and preconditions
necessary to make reusing your Port instance from several threads work fine?

Simply assume that in your above example with using the same
username/password for each call, two years later, business requirements
change and some part of the calls need to be done using a different
username/password combo. Will the person maintaining your code at this
point in time still have the chance find out why the updated code now
breaks in a non-deterministic way (by reading your doc comments or
asking you in person - will you at all be available any more to explain
the reasoning behind the decision you made two years ago)???

Base line: You can easily work around all those issues by using the spec
following its original intention, and this intention is to require
specific handling of Port/Dispatch objects for multi-threaded clients.

The thread-local Port/Dispatch object pattern is a more than viable way
to do so - so it is my clear recommendation to code in this way and keep
away from questionable non-portable coding.

Hope this helps & best regards,

Andreas

> Cheers Cristian

Cristian Chiovari

Hi All

Yes I agree with solution you proposed and this is exactly what happened :) !!!!

"Simply assume that in your above example with using the same username/password for each call, two years later, business requirements change and some part of the calls need to be done using a different username/password combo. "

I inherited a project where a port was shared among multiple calls ( generic user was used to call secured web service) BUT now this changed and each call must be done by the current logged user (because there are some new business constraints)

That is the reason I asked the first question !!!

So the generic user used in the past to attack the WS , is not a solution and sharing the port is wrong in this situation !!!

I hope this thread will help others and thanks Andreas for your time and excellent analysis.

Regards

Cristian.

On 07 Jul 2012, at 14:24, Andreas Loew wrote:

> Hi Cristian, hi everybody else attempted fo follow Cristian's reasoning,
>
> Am 07.07.2012 09:37, schrieb :
>> As i see now things even metro ports might be used by multiple threads .one example is if you use same user name and password for each call. There are Ws that are secured based on a group and each clent application gets its own username and pass. so in this case i do notmsee what might be the problem. also when you use a non secured webservice and all you need is request response...there is no shared state in the port that might put in danger because multiple threads are using the port. What i see problematic is indeed when each request has some particular info place in requestcontext....or as is specified in apache cxf faq. Hope i understood correctly....
> yes, your understanding of how it works definitely is correct now.
>
>
> However, I would still like to strongly advise you (and anybody else reading this out there) against sharing Port and/or Dispatch objects between threads in multi-threaded JAX-WS clients.
>
> With the proposed solution to use the ThreadLocal approach to cache one dedicated Port/Dispatch object per thread, there is a fully spec compliant solution which does only impose quite a low additional overhead of complexity (and also of memory - the JAX-WS Service is the huge object referencing the parsed WSDL contents etc.) to your code.
>
> On the other hand, there is a huge number of disadvantages if you start sharing the Port between threads in your code without any "security measures":
>
> * You leave the grounds of the spec, which clearly states Port/Dispatch must not be expected to be thread safe.
>
> * This basically means you introduce a hard-coded dependency on the particular "proprietary" JAX-WS implementation you are using right now into your code: Simply switch to another implementation (such as from CXF and its "prorietary" thread-safety extension to Metro), and your code might break. This is not the Java and Java EE intention of coding against standards.
>
> * The maintainability of your code becomes questionable at least: When relying onto the thread-safety of a particular Port implementation, can you indeed fully document all the assumptions and preconditions necessary to make reusing your Port instance from several threads work fine?
>
> Simply assume that in your above example with using the same username/password for each call, two years later, business requirements change and some part of the calls need to be done using a different username/password combo. Will the person maintaining your code at this point in time still have the chance find out why the updated code now breaks in a non-deterministic way (by reading your doc comments or asking you in person - will you at all be available any more to explain the reasoning behind the decision you made two years ago)???
>
> Base line: You can easily work around all those issues by using the spec following its original intention, and this intention is to require specific handling of Port/Dispatch objects for multi-threaded clients.
>
> The thread-local Port/Dispatch object pattern is a more than viable way to do so - so it is my clear recommendation to code in this way and keep away from questionable non-portable coding.
>
> Hope this helps & best regards,
>
> Andreas
>
>
>> Cheers Cristian
>

al130959
Offline
Joined: 2005-09-28
Points: 0

Oops,

Am 07.07.2012 00:34, schrieb Andreas Loew:
> (...) and while I am almost 100% certain that CXF JAX-WS Ports are
> thread-safe, (...)
just double-checked my statement about CXF and found the following:

http://cxf.apache.org/faq.html#FAQ-AreJAXWSclientproxiesthreadsafe%3F*

*So basically it is the same with CXF as with Metro - simply go with the
official statement: client proxies are NOT thread safe!

BR,

Andreas
*
===

*Citing the above CXF link:*

Official JAX-WS answer:* No. 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.

*CXF answer:* CXF proxies are thread safe for MANY use cases. The
exceptions are:

* Use of ((BindingProvider)proxy).getRequestContext() - per JAX-WS
spec, the request context is PER INSTANCE. Thus, anything set there
will affect requests on other threads. With CXF, you can do:

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

and future calls to getRequestContext() will use a thread local
request context. That allows the request context to be threadsafe.
(Note: the response context is always thread local in CXF)

* Settings on the conduit - if you use code or configuration to
directly manipulate the conduit (like to set TLS settings or
similar), those are not thread safe. The conduit is per-instance and
thus those settings would be shared. Also, if you use the
FailoverFeature and LoadBalanceFeatures, the conduit is replaced on
the fly. Thus, settings set on the conduit could get lost before
being used on the setting thread.

* Session support - if you turn on sessions support (see jaxws spec),
the session cookie is stored in the conduit. Thus, it would fall
into the above rules on conduit settings and thus be shared across
threads.

* WS-Security tokens - If use WS-SecureConversation or WS-Trust, the
retrieved token is cached in the Endpoint/Proxy to avoid the extra
(and expensive) calls to the STS to obtain tokens. Thus, multiple
threads will share the token. If each thread has different security
credentials or requirements, you need to use separate proxy instances.

For the conduit issues, you COULD install a new ConduitSelector that
uses a thread local or similar. That's a bit complex though.

For most "simple" use cases, you can use CXF proxies on multiple
threads. The above outlines the workarounds for the others

Glen Mazza

Here's what CXF has to say on its thread safety:
http://cxf.apache.org/faq.html#FAQ-AreJAXWSclientproxiesthreadsafe%3F

Glen

On 7/6/2012 6:34 PM, Andreas Loew wrote:
> Hi Cristian,
>
> as I wrote in my very first reply, the thread safety of Port objects
> depends on the particular JAX-WS implementation that you are using.
> The JAX-WS specification itself does NOT require Port and Dispatch
> objects to be thread-safe.
>
> So not every statement in the forums must be 100% true:
>
> While it might be possible that WLS JAX-WS Ports are thread-safe (not
> certain at all, as I haven't used WLS JAX-WS yet - although WLS JAX-WS
> is based on Metro...), and while I am almost 100% certain that CXF
> JAX-WS Ports are thread-safe, Metro's Port objects definitely are NOT
> thread-safe:
>
> You get access to the BindingProvider object through the port, which
> in Metro is an unsynchronized HashMap (at least, it was in Metro 1.4
> when I last checked, but I believe it still is).
>
> As you can e.g. do the following:
>
> | Map context= ((BindingProvider)
> port).getRequestContext();
> Map> headers= new HashMap List>();
> headers.put("Username", Collections.singletonList("yourusername"));
> headers.put("Password", Collections.singletonList("yourpassword"));
> |
>
> to set a per-request username and password, and this might be
> different username/password combos for different requests, or, to give
> another sample, access the response's HTTP headers:
>
> headers = (Map>) ((BindingProvider)
> port).getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS);
>
> I hope it becomes quite clear that you better NOT share the port
> between several threads - at least not in case you are interested in
> any request or response info contained in the BindingProvider map.
>
> Hope this further clarifies it...
>
> Best regards & have a nice weekend,
>
> Andreas
>
>
> Am 06.07.2012 19:45, schrieb Cristian Chiovari:
>>
>> Regarding the thread safety this is what i found on an oracle forum :
>>
>> https://forums.oracle.com/forums/thread.jspa?threadID=2260797
>>
>> "
>> mac24nz wrote:
>> Do I need to be concerned about the calls to getPort()? do I need a
>> Port instance for each thread, or is 1 instance of getPort sufficient
>> for all threads?
>>
>> If you call getPort() in the method that needs it, you will have no
>> threading issues. But since the port must have no state, a single
>> port object should be able to be shared by multiple threads without
>> collision in the same way a Stateless EJB is thread safe.
>>
>> Let me put it in another way: I've never had issues with it either
>> way, if you want to rely on what I say to be true.
>>
>> "
>>
>> So is the port thread safe ? I start to be confused :))
>>
>> Regards...
>>
>> On 03 Jul 2012, at 17:23, Andreas Loew wrote:
>>
>>> Hi Cristian,
>>>
>>> Am 03.07.2012 15:55, schrieb Cristian Chiovari:
>>>> Well I guess understand and sorry for prolonging this discussion:
>>>>
>>>> public final class ThreadContext {
>>>>
>>>> private static ThreadLocal threadLocal = new
>>>> ThreadLocal();
>>>>
>>>> private Port1 port1;
>>>> private Port2 port2;
>>>> ....
>>>> private Port3 port3;
>>>> private ThreadContext() {
>>>> super();
>>>> }
>>>> public static ThreadContext getInstance() {
>>>> ThreadContext result;
>>>> result = (ThreadContext) threadLocal.get();
>>>> if (result == null) {
>>>> result = new ThreadContext();
>>>> threadLocal.set(result);
>>>> }
>>>> return result;
>>>> }
>>>>
>>>> .............
>>>> setter and getter for ports
>>>> ............
>>>> public static void unset() {
>>>> threadLocal.remove();
>>>> }
>>>> }
>>>>
>>>> public class ThreadContextInitFilter implements Filter{
>>>>
>>>> public void init(FilterConfig filterConfig) throws
>>>> ServletException {
>>>> }
>>>> public void doFilter(ServletRequest servletRequest,
>>>> ServletResponse servletResponse,FilterChain chain) throws
>>>> IOException, ServletException {
>>>> ThreadContext threadContext = ThreadContext.getInstance();
>>>> // get the port from a static service !
>>>> threadContext.setPort1 (port1);
>>>> chain.doFilter(servletRequest, servletResponse);
>>>> }
>>>> }
>>>> }
>>> Yes indeed - the ThreadContext pattern is what I was targetting at,
>>> although I am somewhat wondering why - when we are looking at the
>>> web app as WS client use case - you should like to complicate things
>>> and use a servlet Filter?
>>>
>>> At least as long as you call into synchronous web service methods on
>>> the remote end, you can theoretically do the whole WS client
>>> handling within a single client (Servlet) class, which
>>>
>>> * creates the private static Service instance in a static
>>> constructor or during the HttpServlet init() method (which is
>>> guaranteed to be called in a thread-safe manner)
>>> * only use local method variables (no instance variables!) to work
>>> with the ThreadContext to get and dispose/remove your Port
>>> instance during your request processing method (doGet() or
>>> doPost(), as you like) - if you do so, your code is also
>>> perfectly thread-safe
>>>
>>> * if you do a more complex scenario and run into the need to store
>>> some state between methods, delegate from the servlet to a simple
>>> POJO class which then implements the WS client, and create and
>>> destruct a new instance of this light-weight POJO for every
>>> request using CDI bean class scope @Dependent - like the Spring
>>> scope="prototype" pattern would do for a Spring bean in case you
>>> are more familiar with that
>>> * the POJO then does not need to be thread-safe any more, but
>>> should still use a singleton private static Service instance and
>>> get/dispose the Port from the ThreadContext
>>>
>>>> There are some people that are against using ThreadLocal however
>>>> that is another discussion.
>>>> http://stackoverflow.com/questions/7022245/threadlocal-safety-in-weblogi...
>>>>
>>>> http://www.adam-bien.com/roller/abien/entry/how_to_pass_context_with
>>> The people stating their objections here do so out of an "ivory
>>> tower". In *theory*, following the letter of the Spec, the EJB
>>> container would be free to change worker threads whenever (i.e.
>>> immediately before) a new EJB method is being called into - but in
>>> practice, I have never seen any real world implementation that does
>>> so - why should it? It would run into all kinds of issues internally
>>> - guess what: The EJB container typically manages the mapping
>>> between its worker threads calling into transactional EJBs and its
>>> transaction context in the exact same way by using ThreadLocals, and
>>> nobody would have any interest in or advantage from changing this
>>> mapping at every call into a new EJB method.
>>>
>>> So yes, in the "ivory tower", using ThreadLocals within the EJB
>>> container could theoretically fail, but believe me - there is no
>>> real reason to assume that this a realistic scenario and will ever
>>> happen.
>>>
>>>> What do you think about using @WebServiceRef ?
>>>> http://docs.oracle.com/cd/E15051_01/wls/docs103/webserv/client.html#wp23...
>>>>
>>> I don't really get the point of what/why you are asking - You should
>>> definitely use this to annotate the static variable within your
>>> Servlet class which is to hold the Singleton thread-safe Service
>>> object representing your target WS for the call.
>>>
>>>> Many thanks !
>>> As I am currently on long-term sick leave and read my e-mails right
>>> now for my personal distraction, you are more than welcome to
>>> receive some insights from me for free. ;-)
>>> In case you would like to receive regular Java consulting on a daily
>>> basis, you will of course need to engage Oracle Advanced Customer
>>> Services (ACS)... :-)
>>>
>>> Best regards from Germany,
>>>
>>> Andreas
>>>
>>>> On Tue, Jul 3, 2012 at 2:47 PM, Andreas Loew
>>>> > wrote:
>>>>
>>>> Hi Cristian,
>>>>
>>>> Am 03.07.2012 14:22, schrieb Cristian Chiovari:
>>>>
>>>> What i have used in the past was done based on
>>>> http://commons.apache.org/pool/ .So when the web app started
>>>> the pool was initialized with a pre configured number of
>>>> instance services. (Ports were created each time ....but as
>>>> i understood they might be cached as well)
>>>>
>>>> This is NOT AT ALL needed! You can create just one single static
>>>> Service instance per WSDL: Any single Service object is fully
>>>> thread-safe and can be shared by as many concurrent threads as
>>>> you like. So "caching" a Service basically means making it a
>>>> static property of your client class, nothing more. Therefore,
>>>> this single object also needs to be initialized only once from
>>>> the WSDL.
>>>>
>>>>
>>>> Just thinking that another solution is to use a dynamic pool
>>>> for ports that can be increase when needed and decreased
>>>> when there is no load
>>>>
>>>> A dynamic pool of Port/Dispatch objects would be an "ideal"
>>>> solution, but as stated before, particularly in an environment
>>>> where your WS client is running from within a Java EE container
>>>> and you therefore have no direct control about the number of
>>>> worker threads from your WorkManager (i.e. either your HTTP
>>>> session pool, EJB pool, or maybe even both depending on the call
>>>> scenarios), I'd rather recommend the ThreadLocal solution: It is
>>>> very simple as far as the codebase is concerned, and - from my
>>>> experience - still tolerable regarding the amount of memory used
>>>> (again, the Service instance is the big object, not the Port).
>>>>
>>>> This means use a lazily initialized static ThreadLocal to cache
>>>> a dedicated Port object to be used from the current worker
>>>> thread. Running the app for a while, successively all the
>>>> threads from your WorkManager's thread pool (HTTP session pool,
>>>> EJB pool) will have their thread's dedicated Port object created
>>>> and cached, and these will then be reused once the same worker
>>>> thread is reassigned by the container WorkManager to execute
>>>> another WS client request of the same sort...
>>>>
>>>> Did I make myself clear enough now? Unfortunately, I don't have
>>>> any code sample at hand which is simple enough to post it here...
>>>>
>>>> HTH & BR,
>>>>
>>>> Andreas
>>>>
>