• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 247
  • Last Modified:

Java few questions

All,

I have some java questions which basically I am struggling with but could not get to answers..

1). Singleton Pattern:

I guess there are 2 ways to implement it:
1).
public class A {
 private static instance;

public static A getInstance() {
 if(instance==null) {
    A instance = new A():
  }

return instance;

 }
}


But of-course this is a problem in multi-thread env -- so synchronizing the getInstance method is an option -- but ofcourse synchronizing will degrade the performance..

Just synchronizing an object A by doing

if (instance == null)
synchronizing(A.class) {
 A instance = new A();
}

will work -- but it has some issues .. double locking also has some issues..

so another implementation that might really work is as below

public class A {
 private static instance = new A();

 public static A getInstance() {
  return instance;
 }
}

The above code as I found should avoid multi-thread issues and should work-- I am not sure how?

Can you please explain ---??

If above code is perfect -- should not this be a perfect singleton implementation? no synchronizing, no issues.. not sure why this was not thought earlier? How this code is ensuring single instance?

2). Why is singleton instance needed in JVM? is it only to control number of objects?

so basically, instead of implementing singleton - if we just add more memory (more RAM?? of more hard-drive??) it should work? Is there any other reason of implementing singleton other than controlling the objects? What benefit we get?

3). Singelton should have one instance only -- but if we have cluster env --
so basically -- cluster env means really 2 machines  --- each has its own JVM .. and thus singleton instance on each JVM.. what about if our counter is singleton -- and it is a cluster env.. we don't want to create 2 single instances.. we just want instance per appl.. how to deal with this scenario...

4). synchronzing -- basically means -- lock an object -- if a method in a class in synchronized -- what objects are locked? all objects used in this method? or the whole class object?

so in above scenario --- if I have synchronized getInstance method -- what is locked? Whole A object here (because A is being used) inside the method?

what if A is not being used.. so only objects which are being used will be locked?

5). serlization -- we serialize the objects to let them travel to network.. what does this means?
what is happening when we serialize the objects

basically - if i understand correctly -- all the IO streams can travel --- so text messages -- strings -- anything that is converted to bytes can travel and doesn't need serliaze..

but we want the object to travel (like User--- name, id)   say in cluster of machines -- we need to serliaze -- because this is a object and ser'ling will convert object to ObjectOutputStream -- and thus will able to travel as a regular stream??

6). what is load balacing on machines and cluster? isn't it that cluster env has load balancing? or to do load balancing - we have to create cluster env...??

7). to let the object travel through sockets -- i guess we again will have to serialize the objects correct? if we just say that

A object above implements serlizable --   now this object is marked as serliazble -- so this should travel as a ObjectOutput Stream correct? I don't have to do anything else correct?


thanks
0
irodov
Asked:
irodov
  • 7
  • 6
  • 2
2 Solutions
 
WebstormCommented:
1)

>> public class A {
>>  private static instance = new A();
>>  public static A getInstance() {
>>   return instance;
>>  }
>> }
>> The above code as I found should avoid multi-thread issues and should work-- I am not sure how?
>> Can you please explain ---??
>> 
>> If above code is perfect -- should not this be a perfect singleton implementation? no synchronizing, no issues.. not sure why this was not thought earlier? How this code is ensuring single instance?

>> why this was not thought earlier?
Only by singleton pattern author.
I already use this kind of implementation

>> Can you please explain ---??
>> How this code is ensuring single instance?

In the code above, the instance is created on static initialization of the class (i.e. when the class is loaded),  before any other thread can be created.

0
 
WebstormCommented:
>> 2). Why is singleton instance needed in JVM? is it only to control number of objects?

Some classes need to have one instance only, for example, class containing resource (pictures, data) common to many application classes.

see http://en.wikipedia.org/wiki/Singleton_pattern
0
 
WebstormCommented:
>> 4). synchronzing -- basically means -- lock an object -- if a method in a class in synchronized -- what objects are locked? all objects used in this method? or the whole class object?

synchronized void instanceMethod()
{ ... }

is equivalent to :

void instanceMethod()
{  synchronized(this) {   ...  } }



static synchronized void classMethod() // in class A for example
{ ... }

is equivalent to :

void classMethod()
{  synchronized(A.class) {   ...  } }


0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
WebstormCommented:
>> 5). serlization -- we serialize the objects to let them travel to network.. what does this means? what is happening when we serialize the objects

When an object is serialized (writing object), it's converted to byte sequence containing the object class name, and all object attributes. Any attribute being an object is also converted to byte sequence.

When an object is de-serialized (reading object), the class name is read, a new instance of that class is created (you need the corresponding .class to be loaded when you read an object), and attributes are initialized to what is read.

see
http://java.sun.com/docs/books/tutorial/essential/io/serialization.html
http://mindprod.com/jgloss/serialization.html
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> so another implementation that might really work is as below

Well, *perhaps* not if you have more than one class-loader.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
I prefer public static synchronized A getInstance ()

>> I don't have to do anything else correct?

Make sure all data-members it has are either primitive or Serializable.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> if a method in a class in synchronized -- what objects are locked?

Only access to that method is locked for that object, meaning that another thread cannot call the same method on the same object.
0
 
irodovAuthor Commented:
well, so
webstorm is saying that better implementation is

public class A {
 private static a = new A();

public static getInstance() {
return a;
}

}

and mayan is saying

synchronizing getInstance is better

I am not sure what exactly is problem in private static a = new A();

mayan: what do you mean more than one class loaders? when will this not work.. can you please describe more?

webstorm -- you said that this instance is created when the class is loaded.. what do you mean -- when JVM startup, this class creates the instance?

can you please help me understanding what is wrong in this way and in what circumstances it works?

0
 
WebstormCommented:
>> you said that this instance is created when the class is loaded.. what do you mean -- when JVM startup, this class creates the instance?

Class is loaded as necessary by the JVM, either explicitly (using Class.forName, or ClassLoader) or implicitly when the class is first used (using a static member (calling method, using field), or creating a new instance).
In this case, the instance will be created the first time you call getInstance() method.
0
 
irodovAuthor Commented:
ok!

I guess i have to read websites to understand problem mayan is saying if we implement  singleton using the other way (of instantiating constructor at static variable declaration)..
or if you can explain me -- wha is wrong in doing this way..

basically -- what I understood is

there are only 2 ways to implement singleton perfecttly..

1). synchronizing
2). instantiating at static declaration ..

in (1), I don't see any issues..
in (2), mayan is saying that there is an issue in certain scenario's -- this is what i want to understand...

also in (2), mayan said

>>Make sure all data-members it has are either primitive or Serializable.

want to understand why..
as serialiable explained by webstorm -- it is really for converting the objects to bytes sequence-- so basically
if i have a A class which bunch of object variables...

A.class if declared Serialiable -- will be converted to byte sequence and all associated object variables will be converted to byte sequence as well .. and somehow (not sure how) -- these object variables will be associated to a A.class byte sequence correct?

why in singleton i have to worry about Serialization?

also, in (1) approach ---

if i synchronize getInstance ---
it is basically than locking the this object (which in this case would be A object..

so basically, it is really locking the whole A object -- and thus A object cannot be used by multiple threads correct?

what about other methods in A class --- (non-synchronized methods) -- can they be used?

webstorm, you said:

synchronized void instanceMethod()
{ ... }

is equivalent to :

void instanceMethod()
{  synchronized(this) {   ...  } }

if I have a class A

public class A {

synchronized void instanceMethod()
{
  // do something -- don't need to use A directly..
}
}

Now as you said, really "this" object is locked here --
what do you mean ---

Like, if some other class is doing

A a = new A();
a.instanceMethod();

so is "a" locked here....

but with static --- whole A.class is locked.. so no method can be used in A.class??

please help me understand concepts.. i know some of them are basics.. just trying to understand them as much as possible..

thanks
0
 
Mayank SAssociate Director - Product EngineeringCommented:
You don't have to worry about serialization specifically in singleton - it has nothing to do with it. Basically if you have a class:

class A
{
  private int a ;
  private B b ; // complex data-type
}

Here, if B is not serializable, then A can also not be serialized because while serializing A, you need to serialize all its data-members too.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> what about other methods in A class --- (non-synchronized methods) -- can they be used?

Yes.
0
 
WebstormCommented:
>> so basically, it is really locking the whole A object -- and thus A object cannot be used by multiple threads correct?
synchronized( <object> )  only suspend other threads trying to do the same  synchronized( <object> )  on the same object, while the owner is in the {...} block.
So calling a synchronized instance method prevent another thread from calling it at the same time, but other threads can call other non-synchronized instance methods.

>> so is "a" locked here....
yes
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 7
  • 6
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now