I am reading Esteban Herrera's Java 8 Programmer II Study Guide. I already understand the keyword "synchronized," but not "volatile." In the first chapter, the author makes the case for the "volatile" keyword. First, he points out an issue with the following code.  class Singleton {     private static Singleton instance;     private Singleton() { }     public static Singleton getInstance() {         if(instance == null) {             synchronized (Singleton.class) {                 if(instance == null) {                     instance = new Singleton();                 }             }         }         return instance;     } }   He calls the above code imperfect, arguing, "The JVM, or sometimes the compiler, can optimize the code by reordering or caching the value of variables (and not making the updates visible)." He recommends adding the volatile keyword to the Singleton instance field because this ensures that its read and write operations will be atomic rather than cached in the case of multiple threads.  I do not fully understand Herrera's argument. What does it mean to reorder the value of variables, and why would this be a problem? What does it mean for read/write operations in multiple threads to be atomic, and why is this necessary? Every explanation that I have found online is likewise full of jargon. Can anyone explain the volatile keyword in layman's terms without assuming a prior understanding of the above terms?
12194
At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found . Given the detail in which that article explains the keyword in question, do you ever use it or could you ever see a case in which you could use this keyword in the correct manner?
8697
While looking at online code samples, I have sometimes come across an assignment of a String constant to a String object via the use of the new operator.  For example:  String s; ... s = new String("Hello World");   This, of course, compared to  s = "Hello World";   I'm not familiar with this syntax and have no idea what the purpose or effect would be.  Since String constants typically get stored in the constant pool and then in whatever representation the JVM has for dealing with String constants, would anything even be allocated on the heap?
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?)
34669
I have a Map which is to be modified by several threads concurrently.   There seem to be three different synchronized Map implementations in the Java API:   Hashtable Collections.synchronizedMap(Map) ConcurrentHashMap   From what I understand, Hashtable is an old implementation (extending the obsolete Dictionary class), which has been adapted later to fit the Map interface. While it is synchronized, it seems to have serious  and is discouraged for new projects.  But what about the other two? What are the differences between Maps returned by Collections.synchronizedMap(Map) and ConcurrentHashMaps? Which one fits which situation?
52524
So I was making a class the other day and used Eclipse's method to create the equals method when I realized that it generated the following working code:  class Test {   private int privateInt;   [...]   public boolean equals(Object obj) {     [...]     Test t = (Test) obj;     if ( t.privateInt == privateInt ) {     [...]   } }   t.privateInt..???? It's suppose to be private! So I guess there is one more field visibility other than private, protected, package protected and public.  So what is happening here? How is this called? Where would somebody use this? Doesn't this break encapsulation? What if the class didn't have a mutator and I changed this? Does this happen to C++ as well? Is this an OO idiom? If not, then why did Java do it?  Generally, where can I find information about this?  Thank you.
32352
I saw this keyword for the first time and I was wondering if someone could explain to me what it does.   What is the continue keyword? How does it work? When is it used?
104079
Is it possible to chain static methods together using a static class? Say I wanted to do something like this:  $value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();   . . . and obviously I would want $value to be assigned the number 14. Is this possible?  Update: It doesn't work (you can't return "self" - it's not an instance!), but this is where my thoughts have taken me:  class TestClass {     public static $currentValue;      public static function toValue($value) {         self::$currentValue = $value;     }      public static function add($value) {         self::$currentValue = self::$currentValue + $value;         return self;     }      public static function subtract($value) {         self::$currentValue = self::$currentValue - $value;         return self;     }      public static function result() {         return self::$value;     } }   After working that out, I think it would just make more sense to simply work with a class instance rather than trying to chain static function calls (which doesn't look possible, unless the above example could be tweaked somehow).
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
49579
I have the following C# singleton pattern, is there any way of improving it?       public class Singleton&lt;T&gt; where T : class, new()     {          private static object _syncobj = new object();         private static volatile T _instance = null;         public static T Instance         {             get             {                 if (_instance == null)                 {                     lock (_syncobj)                     {                         if (_instance == null)                         {                             _instance = new T();                         }                     }                 }                 return _instance;             }         }          public Singleton()         { }      }   Preferred usage example:   class Foo : Singleton&lt;Foo&gt;  { }    Related:
106358
Most of what I have read about retry operations is that they are vaguely complicated and indepth. I have written the code below which seems to accomplish this without too much confusion - I'm wondering if there are any pitfalls I am not seeing here.   The class uses a top-level schedulable class, which calls a queueable class to make the callout, and if the callout is unsuccessful, it just schedules the top level class again five minutes later. After testing it appears this works indefinitely.   A simple string token, assigned at the first invocation, is also passed between the classes, and I have tested and found that the token does persist, even when runs are scheduled for a later time.   Thanks for helpful thoughts!  public class SelfServe implements Schedulable {      public String Token = null;      public void execute(SchedulableContext ctx) {                  RetrieveMachineDetails Job = new RetrieveMachineDetails();             Job.Token = Token;             System.enqueueJob(Job);      }           public class RetrieveMachineDetails implements Queueable, Database.AllowsCallouts {          public String Token = null;          public void execute(QueueableContext context){                                            Http http = new Http();             HttpRequest request = new HttpRequest();                             request.setEndpoint('https://app.endpoint.com/api');                     request.setMethod('POST');                     request.setHeader('Content-Type', 'application/json;charset=UTF-8');                                      request.setBody('{"query":  "$message_=\'METRIC\' &amp;&amp; $tier=\'customer\' "}');                                                                                                                                                                                    HttpResponse response = http.send(request);                            if (response.getStatusCode() == 200) {                 //do stuff                  }              else { //retry                  DateTime Dt = system.now().addMinutes(5);                                String day = string.valueOf(Dt.day());                                        String month = string.valueOf(Dt.month());                                          String hour = string.valueOf(Dt.hour());                                       String minute = string.valueOf(Dt.minute());                                                       String year = string.valueOf(Dt.year());                                   String ScheduledTime = '0 ' + minute + ' ' + hour + ' ' + day + ' ' + month + ' ?' + ' ' + year;                  SelfServe Job = new SelfServe();                     Job.Token = Token;                 System.schedule('SelfServe Job'+Dt, ScheduledTime, Job);              }         }        }  }
18449
Hopefully a simple question. Take for instance a Circularly-linked list:  class ListContainer {   private listContainer next;   &lt;..&gt;    public void setNext(listContainer next)   {     this.next = next;   } }  class List {   private listContainer entry;   &lt;..&gt; }   Now since it's a circularly-linked list, when a single elemnt is added, it has a reference to itself in it's next variable. When deleting the only element in the list, entry is set to null. Is there a need to set ListContainer.next to null as well for Garbage Collector to free it's memory or does it handle such self-references automagically?
68199
What is the difference between using the Runnable and Callable interfaces when designing a concurrent thread in Java, why would you choose one over the other?
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.
1052
Please don't say EHCache or OSCache, etc. Assume for purposes of this question that I want to implement my own using just the SDK (learning by doing). Given that the cache will be used in a multithreaded environment, which datastructures would you use? I've already implemented one using  and , but I'm curious if any of the new concurrent collections would be better candidates.  UPDATE: I was just reading through  when I found this nugget:     If you need constant-time access and want to maintain the insertion order, you can't do better than a LinkedHashMap, a truly wonderful data structure. The only way it could possibly be more wonderful is if there were a concurrent version. But alas.   I was thinking almost exactly the same thing before I went with the LinkedHashMap + Collections#synchronizedMap implementation I mentioned above. Nice to know I hadn't just overlooked something.  Based on the answers so far, it sounds like my best bet for a highly concurrent LRU would be to extend  using some of the same logic that LinkedHashMap uses.
17715
When writing multithreaded applications, one of the most common problems experienced is race conditions.    My questions to the community are:  What is the race condition? How do you detect them? How do you handle them? Finally, how do you prevent them from occurring?
72858
I am trying to learn how to specify class constructors in Java. I am starting to understand that they specify the types of instance variables of objects made from that class. They also can be used to set the instance variable initial values. The follow example is from the Java tutorial on Sun's website:  public Bicycle(int startCadence, int startSpeed, int startGear) {     gear = startGear;     cadence = startCadence;     speed = startSpeed; }   Where in your classes source code should you put the constructor(s)?  Are these arguments the names of the variables?: (int startCadence, int startSpeed, int startGear) or are gear, cadence and speed the names of the variables?  What is the difference between (int startCadence, int startSpeed, int startGear) and gear, cadence and speed?  In the unlikely event that my instructor or any administrator from Salt Lake Community College ever comes across this question, let me make my intentions clear. This question is posted in the greatest spirit of academic honesty. I ask this question to seek general advice and help in understanding the proper way to use the Java programming language. I in no way use the work of others and represent it as my own work. I use the answers provided here as a general aid in my understanding. I do all my own work and do not copy work provided by people answering my question.
109028
I'm unclear about the true meaning in the definitions for IMMUTABLE, VOLATILE and STABLE functions.  I read the documentation, specifically the definitions of each.       IMMUTABLE indicates that the function cannot modify the database and   always returns the same result when given the same argument values; that is, it does not do database lookups or otherwise use   information not directly present in its argument list. If this option   is given, any call of the function with all-constant arguments can be   immediately replaced with the function value.      STABLE indicates that the function cannot modify the database, and   that within a single table scan it will consistently return the same   result for the same argument values, but that its result could change   across SQL statements. This is the appropriate selection for functions   whose results depend on database lookups, parameter variables (such as   the current time zone), etc. (It is inappropriate for AFTER triggers   that wish to query rows modified by the current command.) Also note   that the current_timestamp family of functions qualify as stable,   since their values do not change within a transaction.      VOLATILE indicates that the function value can change even within a   single table scan, so no optimizations can be made. Relatively few   database functions are volatile in this sense; some examples are   random(), currval(), timeofday(). But note that any function that has   side-effects must be classified volatile, even if its result is quite   predictable, to prevent calls from being optimized away; an example is   setval().   My confusion comes in with the condition for IMMUTABLE and STABLE that the function ALWAYS or CONSISTENTLY returns the same result given the same arguments.    The IMMUTABLE definition states that the function does not database lookups or otherwise use information not directly present in its argument list.  So, to me, that means such functions are used to manipulate data provided by the client, and should not have SELECT statements...although that just sounds a bit odd to me.  With STABLE, the definition is similar in that it says it should consistently return the same result.  So, to me, that means that everytime the function is called with the same arguments, it should return the same results (same exact rows, every single time).  So, to me...that means that any function that performs a SELECT on a table or tables that can be updated, should only be volatile.  But, again...that doesn't sound right to me.  Bringing this back to my use-case, I am writing functions that perform SELECT statements with multiple JOIN's on tables that are constantly being added to, so the function calls would be expected to return different results each time it's called, even with the same arguments.  So, does that mean that my functions should be VOLATILE?  Even though the documentation indicates relatively few database functions are volatile in this sense?  Thank you!