I've noticed in virtually all examples I've seen that locks on instances are used as follows  public class Foo {    readonly object locker = new Object();    public void DoSomething() {       lock(locker) {          //...       }    }    public void DoSomethingElse() {       lock(locker) {          //...       }    } }   This is very useful when multiple threads might have access to the same instance and you want its methods to be atomic relative to each other.  In my experiments, it would work just as well however if I did a lock(this) rather than having the locker object. Is there something I'm missing or is that perfectly fine?
8134
The  says that public class SomeObject {   public void SomeOperation()   {     lock(this)     {       //Access instance variables     }   } }  is &quot;a problem if the instance can be accessed publicly&quot;. I'm wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?
78599
Let's say I'm writing a PHP (>= 5.0) class that's meant to be a singleton.  All of the docs I've read say to make the class constructor private so the class can't be directly instantiated.  So if I have something like this:  class SillyDB {   private function __construct()   {    }    public static function getConnection()   {    } }   Are there any cases where __construct() is called other than if I'm doing a   new SillyDB()    call inside the class itself?    And why am I allowed to instantiate SillyDB from inside itself at all?
4388
I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:  In a constructor:  public Light(Vector v) {     this.dir = new Vector(v); }   Elsewhere  public void SomeMethod() {     Vector vec = new Vector();     double d = (vec * vec) - (this.radius * this.radius); }
103196
In Java, the idiomatic way to declare critical sections in the code is the following:  private void doSomething() {   // thread-safe code   synchronized(this) {     // thread-unsafe code   }   // thread-safe code }   Almost all blocks synchronize on  this, but is there a particular reason for this? Are there other possibilities? Are there any best practices on what object to synchronize on? (such as private instances of Object?)
77567
I've read in the  and the  the mention of inner classes. What is their purpose?  I see in the Apex Workbook that they used private variables and setter/getter methods in the inner class, but why didn't they just do that in the outer class with a constructer, getter, and setter?
55175
I'm implementing compareTo() method for a simple class such as this (to be able to use Collections.sort() and other goodies offered by the Java platform):  public class Metadata implements Comparable&lt;Metadata&gt; {     private String name;     private String value;  // Imagine basic constructor and accessors here // Irrelevant parts omitted }   I want the natural ordering for these objects to be: 1) sorted by name and 2) sorted by value if name is the same; both comparisons should be case-insensitive. For both fields null values are perfectly acceptable, so compareTo must not break in these cases.   The solution that springs to mind is along the lines of the following (I'm using "guard clauses" here while others might prefer a single return point, but that's beside the point):  // primarily by name, secondarily by value; null-safe; case-insensitive public int compareTo(Metadata other) {     if (this.name == null &amp;&amp; other.name != null){         return -1;     }     else if (this.name != null &amp;&amp; other.name == null){         return 1;     }     else if (this.name != null &amp;&amp; other.name != null) {         int result = this.name.compareToIgnoreCase(other.name);         if (result != 0){             return result;         }     }      if (this.value == null) {         return other.value == null ? 0 : -1;     }     if (other.value == null){         return 1;     }      return this.value.compareToIgnoreCase(other.value); }   This does the job, but I'm not perfectly happy with this code. Admittedly it isn't very complex, but is quite verbose and tedious.  The question is, how would you make this less verbose (while retaining the functionality)? Feel free to refer to Java standard libraries or Apache Commons if they help. Would the only option to make this (a little) simpler be to implement my own "NullSafeStringComparator", and apply it for comparing both fields?  Edits 1-3: Eddie's right; fixed the "both names are null" case above  About the accepted answer  I asked this question back in 2009, on Java 1.6 of course, and at the time  was my preferred accepted answer. I never got round to changing that until now (2017).  There are also —a 2009 Apache Commons Collections one and a 2013 Guava one, both posted by me—that I did prefer at some point in time.  I now made the clean  the accepted answer. That should definitely be preferred if on Java 8, and these days Java 8 should be available to nearly all projects.
76493
I am working on creating an immutable class. I have marked all the properties as read-only.   I have a list of items in the class. Although if the property is read-only the list can be modified.   Exposing the IEnumerable of the list makes it immutable. I wanted to know  what is the basic rules one has to follow to make a class immutable ?
3920
Using C# and WPF under .NET (rather than  or console), what is the correct way to create an application that can only be run as a single instance?  I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are.  The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.
9009
So lets say I have this interface:  public interface IBox {    public void setSize(int size);    public int getSize();    public int getArea();   //...and so on }   And I have a class that implements it:  public class Rectangle implements IBox {    private int size;    //Methods here }   If I wanted to use the interface IBox, i can't actually create an instance of it, in the way:  public static void main(String args[]) {     Ibox myBox=new Ibox(); }   right? So I'd actually have to do this:  public static void main(String args[]) {     Rectangle myBox=new Rectangle(); }   If that's true, then the only purpose of interfaces is to make sure that the class which implements an interface has got the correct methods in it as described by an interface? Or is there any other use of interfaces?
61737
I would like to use Class.newInstance() but the class I am instantiating does not have a nullary constructor. Therefore I need to be able to pass in constructor arguments. Is there a way to do this?
78110
Is there any advantage of using     instead of  ?   As far as I can tell the following fragments are almost equivalent:  1. Semaphore  final Semaphore sem = new Semaphore(0); for (int i = 0; i &lt; num_threads; ++ i) {   Thread t = new Thread() {     public void run()     {       try       {         doStuff();       }       finally       {         sem.release();       }     }   };   t.start(); }  sem.acquire(num_threads);   2: CountDownLatch  final CountDownLatch latch = new CountDownLatch(num_threads); for (int i = 0; i &lt; num_threads; ++ i) {   Thread t = new Thread() {     public void run()     {       try       {         doStuff();       }       finally       {         latch.countDown();       }     }   };   t.start(); }  latch.await();   Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.)  So in what situation might the latch be preferable?
10255
If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway?  For example:  class Program {     static void Main(string[] args)     {         TestRef t = new TestRef();         t.Something = "Foo";          DoSomething(t);         Console.WriteLine(t.Something);     }      static public void DoSomething(TestRef t)     {         t.Something = "Bar";     } }   public class TestRef {     public string Something { get; set; } }   The output is "Bar" which means that the object was passed as a reference.
88092
POSIX allows mutexes to be recursive. That means the same thread can lock the same mutex twice and won't deadlock. Of course it also needs to unlock it twice, otherwise no other thread can obtain the mutex. Not all systems supporting pthreads also support recursive mutexes, but if they want to be .  Other APIs (more high level APIs) also usually offer mutexes, often called Locks. Some systems/languages (e.g. Cocoa Objective-C) offer both, recursive and non recursive mutexes. Some languages also only offer one or the other one. E.g. in Java mutexes are always recursive (the same thread may twice "synchronize" on the same object). Depending on what other thread functionality they offer, not having recursive mutexes might be no problem, as they can easily be written yourself (I already implemented recursive mutexes myself on the basis of more simple mutex/condition operations).  What I don't really understand: What are non-recursive mutexes good for? Why would I want to have a thread deadlock if it locks the same mutex twice? Even high level languages that could avoid that (e.g. testing if this will deadlock and throwing an exception if it does) usually don't do that. They will let the thread deadlock instead.  Is this only for cases, where I accidentally lock it twice and only unlock it once and in case of a recursive mutex, it would be harder to find the problem, so instead I have it deadlock immediately to see where the incorrect lock appears? But couldn't I do the same with having a lock counter returned when unlocking and in a situation, where I'm sure I released the last lock and the counter is not zero, I can throw an exception or log the problem? Or is there any other, more useful use-case of non recursive mutexes that I fail to see? Or is it maybe just performance, as a non-recursive mutex can be slightly faster than a recursive one? However, I tested this and the difference is really not that big.
67360
Edit:    From another question I provided an answer that has links to a lot of questions/answers about singletons:   So I have read the thread  And the argument still rages.  I see Singletons as a Design Pattern (good and bad). The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!).  So the main questions that need to be answered are:   When should you use a Singleton How do you implement a Singleton correctly   My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses.  So get the ball rolling: I will hold my hand up and say this is what I use but probably has problems. I like "Scott Myers" handling of the subject in his books "Effective C++"     Good Situations to use Singletons (not many):         Logging frameworks   Thread recycling pools      /*  * C++ Singleton  * Limitation: Single Threaded Design  * See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf  *      For problems associated with locking in multi threaded applications  *  * Limitation:  * If you use this Singleton (A) within a destructor of another Singleton (B)  * This Singleton (A) must be fully constructed before the constructor of (B)  * is called.  */ class MySingleton {     private:         // Private Constructor         MySingleton();         // Stop the compiler generating methods of copy the object         MySingleton(MySingleton const&amp; copy);            // Not Implemented         MySingleton&amp; operator=(MySingleton const&amp; copy); // Not Implemented      public:         static MySingleton&amp; getInstance()         {             // The only instance             // Guaranteed to be lazy initialized             // Guaranteed that it will be destroyed correctly             static MySingleton instance;             return instance;         } };   OK. Lets get some criticism and other implementations together. :-)
75794
I've got a bunch of properties which I am going to use read/write locks on. I can implement them either with a try finally or a using clause.  In the try finally I would acquire the lock before the try, and release in the finally. In the using clause, I would create a class which acquires the lock in its constructor, and releases in its Dispose method.  I'm using read/write locks in a lot of places, so I've been looking for ways that might be more concise than try finally. I'm interested in hearing some ideas on why one way may not be recommended, or why one might be better than another.  Method 1 (try finally):  static ReaderWriterLock rwlMyLock_m  = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime {     get     {         rwlMyLock_m .AcquireReaderLock(0);         try         {             return dtMyDateTime_m         }         finally         {             rwlMyLock_m .ReleaseReaderLock();         }     }     set     {         rwlMyLock_m .AcquireWriterLock(0);         try         {             dtMyDateTime_m = value;         }         finally         {             rwlMyLock_m .ReleaseWriterLock();         }     } }   Method 2:  static ReaderWriterLock rwlMyLock_m  = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime {     get     {         using (new ReadLock(rwlMyLock_m))         {             return dtMyDateTime_m;         }     }     set     {         using (new WriteLock(rwlMyLock_m))         {             dtMyDateTime_m = value;         }     } }  public class ReadLock : IDisposable {     private ReaderWriterLock rwl;     public ReadLock(ReaderWriterLock rwl)     {         this.rwl = rwl;         rwl.AcquireReaderLock(0);     }      public void Dispose()     {         rwl.ReleaseReaderLock();     } }  public class WriteLock : IDisposable {     private ReaderWriterLock rwl;     public WriteLock(ReaderWriterLock rwl)     {         this.rwl = rwl;         rwl.AcquireWriterLock(0);     }      public void Dispose()     {         rwl.ReleaseWriterLock();     } }
117969
I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write.  However, I was looking through System.Web.Security.Membership using Reflector and found code like this:  public static class Membership {     private static bool s_Initialized = false;     private static object s_lock = new object();     private static MembershipProvider s_Provider;      public static MembershipProvider Provider     {         get         {             Initialize();             return s_Provider;         }     }      private static void Initialize()     {         if (s_Initialized)             return;          lock(s_lock)         {             if (s_Initialized)                 return;              // Perform initialization...             s_Initialized = true;         }     } }   Why is the s_Initialized field read outside of the lock? Couldn't another thread be trying to write to it at the same time? Are reads and writes of variables atomic?
9770
I'm sure you all know the behaviour I mean - code such as:  Thread thread = new Thread(); int activeCount = thread.activeCount();   provokes a compiler warning.  Why isn't it an error?  EDIT:  To be clear: question has nothing to do with Threads.  I realise Thread examples are often given when discussing this because of the potential to really mess things up with them.  But really the problem is that such usage is always nonsense and you can't (competently) write such a call and mean it.  Any example of this type of method call would be barmy.  Here's another:  String hello = "hello"; String number123AsString = hello.valueOf(123);   Which makes it look as if each String instance comes with a "String valueOf(int i)" method.