Volatile keyword: The volatile keyword in java is a keyword only allowed for variables. It ensures that the value of that variable is never cached; it is always read from main memory (reads and writes are atomic). For example, updating a long or double on some JVMs are two step processes, i.e., writing 32 bits twice. If after the initial write the variable is read by a different thread, problems could occur and instability results. The volatile keyword ensures that writes happen-before reads in Java's memory module. Volatile is not a replacement for synchronized, though it can in some situations. Synchronized requires lock on object or method, or can be blocked by awaiting this lock. Volatile does not obtain or release locks on objects, so it has less overhead.
Race Conditions: The standard result of two threads interleaving operations due to the chance that they both read a condition and entered a block of code where only one thread should have gone. An example would be having a hashmap, and checking for a key. If the key was not found by thread 1, it enters an unsynchronized code block that adds the key and the corresponding value to the hashmap. However, if the CPU is lost from thread 1 and switches to thread 2, that key doesn't exist and now there are two threads about to insert potentially different values into the same bucket.
Thread vs Runnable: In general, you don't want to lose a class's ability to inherit behavior from a superclass, which you can lose by extending Thread. Also, class extension is usually done to broaden functionality in a subclass, which, if Thread is only being extended to start a new Thread, is a waste. Thread cannot be started once it's ended, and Runnable can, so Runnable is more efficient. You would have to make a new Thread every time you wanted to run it (additional overhead). Runnables can be executed by Executors repeatedly.
Avoiding NullPointerException: If comparing two strings, for example, dereference the known string literal, i.e., ("dude".equals(string1)) rather than (string1.equals("dude")). If calling toString() results in the same as calling String.valueOf(), use String.valueOf() because it will return null. Use null-safe libraries, like those from Apache-commons. Return Collections.EMPTY_LIST instead of null when possible.
No comments:
Post a Comment