Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

synchronized

Status
Not open for further replies.

DKL01

Programmer
Sep 14, 2000
233
US
Hi,

I really appreciate if anybody can explain what's going on in getInstance method.

public class MLogin
{

private static MLogin instance = null;

public static MLogin getInstance (String address) throws exception
{
if (instance == null)
synchronized(Class("MLogin"))
{
if(instance == null)
instance = new MLogin();
instance.setValue(address);

}
}


public void setValue(address)
{
:
:
}

}
 
No sure where you got this code, but there are some fundamental errors in it :

- There is no class named "exception" - it is "Exception".
- The synchronized method is nonsense - it only makes sense to synch on an object such as "synchronized(this)" - but this would not be valid as the getInstance() method is static.
- There is no method called "Class" in the class.
- The setValue() method does not declare what kind of object "address" is.
- The getInstance() method does not return anything.

So to answer your question - the getInstance() method is not doing anything as it would not even compile ! If you fixed it, then it would return a static instance of the MLogin class - and all calls to it would return a reference to only one MLogin per JVM.
Code:
public class MLogin {

    private static MLogin instance = null;

    public static MLogin getInstance (String address) throws Exception {
		if(instance == null) {
			instance = new MLogin();
			instance.setValue(address);
		}

		return instance;

    }

    public void setValue(String address) {
        //:
        //:
    }

}
 
While putting the code I made mistakes in syntax. Here is the code.

public class MLogin
{

private static MLogin instance = null;

public static MLogin getInstance (String address) throws Exception
{
if (instance == null)
synchronized(Class.forName("MLogin"))
{
if(instance == null)
instance = new MLogin();
instance.setValue(address);

}
}


public void setValue(String address)
{
//some code
}

}
 
Oh, well thanks for wasting my time anyway by posting incorrect code. The code you posted again will still not compile because it does not return anything.

As I said last time getInstance() is doing :

If you fixed it, then it would return a static instance of the MLogin class - and all calls to it would return a reference to only one MLogin per JVM.


Quite why you need to synchronize on the static initializer of MLogin I don't know - the JVM would handle any multi-threaded calls to this class method because it is static, and returns a static class (ie one per JVM).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top