简体   繁体   中英

How would I make a Java class thread safe for XPages

I was writing (re-writing from LS) a Java library of common functions, for example, a method to add a user to a group in the Domino directory. In LotusScript this was done in an agent/script library and concurrent agents were not turned on. So, I did not have to worry about save conflicts if two users invoked the method to add a user to the same group.

In XPages they can run concurrently. So, I was wondering what is the best practice to restrict the method so it was thread-safe. I was initially thinking I was not going to use managed beans since I am not saving any information, just calling this method to add a user to a group. But, I can see that if the method was run concurrently to add a user to the same group there might be a save conflict.

Any suggestions on how to best prevent this? Use an application scoped managed bean and set a flag when the method is running? Or should I just handle this by calling save(false, false) so my document save will fail and I have logic in my code to try again? Or, is there some other best practice to use?

There are 2 approaches that come to my mind. First is to use the synchronized keyword to use Java's internal mechanism. This is perfectly fine when you don't expect much overlap but want a safeguard.

The second one would be more effort and only needed when there is a lot of concurrent action: instead of executing the action add it to a queue object and have a separate threat working through that queue.

You might want to read up on Thinking in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM