Showing posts with label singleton. Show all posts
Showing posts with label singleton. Show all posts

Friday, November 19, 2010

Unsafe Singleton

Many mighy think, is there something called unsafe singleton? Singleton is the property, which lets just only one object floats at a time and there are no more than one object. This singleton program will create more than one object under multi threaded environment, which is totally against rationale.

public class SingletonUnsafeDemo
{
public static void main( String[] args )
{
Thread t1 = new Thread()
{
public void run()
{
System.out.println( "UnsafeSingleton: " + UnsafeSingleton.getInstance() );

}
};

Thread t2 = new Thread()
{
public void run()
{
System.out.println( "UnsafeSingleton: " + UnsafeSingleton.getInstance() );

}
};


t1.start();
t2.start();
}
}

class UnsafeSingleton
{
static UnsafeSingleton instance;

public static UnsafeSingleton getInstance()
{
if ( instance == null )
{
Thread.yield(); // !!

instance = new UnsafeSingleton();
}

return instance;
}
}

Tuesday, August 10, 2010

Round IV

  • Is it possible to access a private method outside it's class? Done using reflection.

  • Iterator and ListIterator

  • how to delete a element from a collection.

  • Singleton, which is threadsafe.

  • difference between statement and preparedStatement object.

  • what is outer join?

  • synchronization - how to synchronize static methods?

  • Jmeter, i did talk more about pathway on NSK and it acutally load balances.

  • any singleton classes available in java. Runtime() I dint say this.

  • Runtime class for finding memory.

  • did ask about synchronizedset, synchronizedlist and synchronizedmap.

  • factory pattern. gave a complete picture about this w.r.t NSJSP manager code.
  • Wednesday, June 9, 2010

    Absolutely Singleton.....

    Many of Java developers know about singleton pattern and how to create it. But, creating a thread safe Singleton is the real absolute singleton. Otherwise, there are chances for ending up with different objects for different threads, which is totally against singleton.

    A sample program given in the discusion here clearly explains how a singleton which is not thread safe can create different objects w.r.t different threads.