[Prévia] [Próxima] [Prévia por assunto] [Próxima por assunto]
[Índice cronológico]
[Índice de assunto]
Re: Metodos static com synchronized
- Subject: Re: Metodos static com synchronized
- From: Francisco Reverbel <reverbel at ime.usp.br>
- Date: Fri, 7 Jun 2002 16:29:37 -0300 (EST)
On Tue, 4 Jun 2002, Christian Willy Asmussen wrote:
> Para esclarecer melhor meu exemplo anterior..
> Gostaria de fazer uma class singleton que seja thread-safe. Fiz assim:
>
> class Singleton
> {
> static Singleton instance;
>
> protected Singleton()
> {
> }
>
> public static Singleton getInstance()
> {
> synchronized(Singleton.class)
> {
> if ( instance == null )
> {
> instance = new Singleton();
> }
> return instance;
> }
> }
> }
>
> Isto garante que que se dois processos concorrentes chamarem getInstance
> ambos vao receber uma referencia para a mesma instancia?
Garante sim. Essa é uma das três alternativas sugeridas na seção
"Statics and Singletons" do livro do Doug Lea (páginas 85 e 86).
As outras duas são mais simples. (Acho que essa parte do livro não
foi para o xerox. Se quiser, pegue comigo.)
Reverbel
>
>
> On Tue, Jun 04, 2002 at 12:30:53PM -0300, Christian Willy Asmussen wrote:
> >
> > Alguem pode me dizer se isto esta certo?
> >
> > Quero fazer metodos "static" de uma classe serem synchronized.
> >
> > class Test
> > {
> > private static boolean lock = false;
> >
> > public static lock()
> > {
> > synchronized(Test.class)
> > {
> > lock = true;
> > }
> > }
> >
> > public static unlock()
> > {
> > synchronized(Test.class)
> > {
> > lock = false;
> > }
> > }
> > }
> >
> >
> > --
> > There is no limit to what you can do
> > if you don't care who gets the credit.
> > - Keynote
>
> --
> There is no limit to what you can do
> if you don't care who gets the credit.
> - Keynote
>