1

I have an Aspect class (spring-aop). I have one advice that gets some parameters and stores it in class fields. Second advice uses these parameters. It is used in functional test, I need to make them thread-safe, because it can be run by several users simultaneously. How can I do it?

public class SomeAspect {
    private String parameters;

    public void saveParameters(JoinPoint jp) {
        Object[] args = jp.getArgs();
        Object firstArg = args[0];
        this.parameters= (String) firstArg;     
    }


    public void useParameters() {
        doSmth(parameters);
    }

}

3
  • 1
    Cam you add a field "private Object mutex" via aspect, and then synchronize(mutex) on that?
    – AlexWien
    Jan 8, 2013 at 12:58
  • Do you want all user threads to use the same parameters, or do you want all users to have their own parameters? In the first case you can just use locking or volatile or AtomicReference. The the second case you can use ThreadLocal or something similar.
    – SamYonnou
    Jan 8, 2013 at 13:35
  • I need second case. I will try ThreadLocal. Thanks Jan 8, 2013 at 14:18

1 Answer 1

0

I think you should use ThreadLocal to store parameters. According to the documentation one request will be processed with one thread, so it should be safe. Documentation is here

2
  • I was thinking about it, but I'm not sure that I am able to set new value to this field during execution advice because thread local is constant. In some cases the value of field could be changed by private methods. I read about volatile, but I have no experience with it Jan 8, 2013 at 13:15
  • But if parameter is changed in method it will change local copy of parameter. I think you can't access that changes outside of method.
    – partlov
    Jan 8, 2013 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.