My colleague gives good advice, and you should follow it.
I would add, in direct response to your question, that masturbating in a public stall with the door locked still may be lewd conduct. Any defense attorney would argue it is not, but there is no guarantee you'll win simply because the door was locked (you definitely lose if no door). Other factors (noise, people in bathroom) would come into play, as would any jury's disgust with the behavior.
Let me give you an example about right to privacy: you have a right to privacy to use a public telephone booth for making a call. Wiretap or other listening is forbidden, per Katz v. US. However, if you leave the door open and shout, you may give up that right. Similarly, if you masturbate in the booth, you have no right to privacy, because that is NOT an activity that the booth conventionally protected. If you masturbated in a public stall with the door open, this is not a case to try in front of a judge or jury.
While therapy may help with your court case, I only recommend it for that reason...if you don't think you have a problem, and can stop doing risky masturbation settings, then that's your decision.
If you have been charged, contact a criminal defense attorney at once. If you have not been arrested contact a behavoral therapist to seek normalization of your behavior. There may be some legal arguments as to the details you mention, but the case is not exactly one you want to have before a jury. You can find a criminal defense attorney in San Francisco by AVVO search or in local ads. Call a couple on Monday, discuss fees, and hire one.
We do not have a client/attorney relationship until you make an appointment, we discuss your case face to face, I accept a retainer, and we explictly agree to enter into representation.
There is no law that explicitly says "Thou shalt not whack off in a public restroom." However there are plenty of other statutes under which you might be charged and some of them require lifetime sexual registration. You need to talk to a lawyer about the circumstances of your case, or several, and then if you have been charged, hire one of them.
I think the issue is whether it was likely that someone would see you. If the bathroom had not doors on the stall, then well....you'd likely be seen. Publicly exposing oneself in a sexual manner is illegal. Public = out in the open or in a public place. Clearly you stated this a public restroom.
Master bation in a public bathroom is not only "frowned upon" but it is illegal.
now stop making admissions on the internet and hire a lawyer.
The above information does not establish an attorney client relationship nor is it meant to provide legal advice.