Results 1 to 4 of 4
  1. #1
    swetu.vc is offline Member
    Join Date
    Nov 2009
    Posts
    1
    Rep Power
    0

    Lightbulb Thread safe without using synchronization

    I am using normal method in multi threaded env. I need to make the method thread safe without using synchronization. Please suggest.

  2. #2
    mrmatt1111's Avatar
    mrmatt1111 is offline Senior Member
    Join Date
    Aug 2009
    Location
    San Jose, CA, USA
    Posts
    320
    Rep Power
    6

    Default

    Use a semaphore then. Or you can use a inner synchronize:

    Java Code:
    private Object lock = new Object();
    
    ...
    
    public void myFunction()
    {
       ...
       synchronized(lock)
       {
          ...
       }
       ...
    }
    Last edited by mrmatt1111; 11-19-2009 at 07:53 PM.
    My Hobby Project: LegacyClone

  3. #3
    Cbani is offline Member
    Join Date
    Jan 2010
    Posts
    90
    Rep Power
    0

    Default

    without using synchronized keyword you can do in this below way

    public class Singleton {
    // Private constructor prevents instantiation from other classes
    private Singleton() {}

    /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance()
    * or the first access to SingletonHolder.INSTANCE, not before.
    */
    private static class SingletonHolder {
    private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
    return SingletonHolder.INSTANCE;
    }
    }

    please go through this link for better idea : Using Synchronized keyword in Singleton Design Pattern

  4. #4
    Cbani is offline Member
    Join Date
    Jan 2010
    Posts
    90
    Rep Power
    0

    Default

    so in the above code snippet getInstance() is a thread safe method....

Similar Threads

  1. Are Local variables thread safe ?
    By samson in forum Threads and Synchronization
    Replies: 6
    Last Post: 12-21-2010, 03:34 PM
  2. Thread Safe Methods / Locks
    By mrhyman in forum Threads and Synchronization
    Replies: 16
    Last Post: 10-24-2008, 10:57 PM
  3. The safe way to stop a thread
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-09-2008, 07:31 PM
  4. Struts framework. Is this thread safe?
    By JavaAl2 in forum Web Frameworks
    Replies: 1
    Last Post: 01-17-2008, 04:01 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •