Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Concurrency torture: testing your code within the Java Memory Model | zeroturnaround.com



Concurrency torture: testing your code within the Java Memory Model | zeroturnaround.com
JCStress is a test harness that is created specifically to fiddle with these kinds of questions.
What we use here is an Actor2_Arbiter1_Test<BitSet, BooleanResult2> interface, which will humbly provide us with method stubs for our two threads and a method to convert a result in a form of BitSet state into a pair of booleans. 

Read full article from Concurrency torture: testing your code within the Java Memory Model | zeroturnaround.com

What is PriorityQueue or priority queue data structure in Java with Example - Tutorial



What is PriorityQueue or priority queue data structure in Java with Example - Tutorial
PriorityQueue is an unbounded Queue implementation in Java, which is based on priority heap. PriorityQueue allows you to keep elements in a particular order, according to there natural order or custom order defined by Comparator interface in Java. Head of priority queue data structure will always contain least element with respect to specified ordering

PriorityQueue in Java is that it's Iterator doesn't guarantee any order, if you want to traverse in ordered fashion, better use Arrays.sort(pq.toArray()) method. PriorityQueue is also not synchronized, which means can not be shared safely between multiple threads, instead it's concurrent counterpart PriorityBlockingQueue is thread-safe and should be used in multithreaded environment. Priority queue provides O(log(n)) time performance for common enqueing and dequeing methods e.g. offer(), poll() and add(), but constant time for retrieval methods e.g. peek() and element().


PriorityQueue keeps least value element at head, where ordering is determined using compareTo() method. It doesn't keep all elements in that order though, only head being least value element is guaranteed. This is in fact main difference between TreeSet and PriorityQueue in Java, former keeps all elements in a particular sorted order, while priority queue only keeps head in sorted order. Another important point to note is that PriorityQueue  doesn't permit null elements and trying to add null elements will result in NullPointerException.
Read full article from What is PriorityQueue or priority queue data structure in Java with Example - Tutorial

java - Boolean.hashCode() - Stack Overflow



java - Boolean.hashCode() - Stack Overflow
The hashCode() method of class Boolean is implemented like this:
public int hashCode() {
    return value ? 1231 : 1237;
}
Why does it use 1231 and 1237? Why not something else?

1231 and 1237 are just two (sufficiently large) arbitrary prime numbers. Any other two large prime numbers would do fine.
Why primes?
Suppose for a second that we picked composite numbers (non-primes), say 1000 and 2000. When inserting booleans into a hash table, true and false would go into bucket 1000 % N resp 2000 % N(where N is the number of buckets).
Now notice that
  • 1000 % 8 same bucket as 2000 % 8
  • 1000 % 10 same bucket as 2000 % 10
  • 1000 % 20 same bucket as 2000 % 20
  • ....
in other words, it would lead to many collisions.
This is because the factorization of 1000 (23, 53) and the factorization of 2000 (24, 53) have so many common factors. Thus prime numbers are chosen, since they are unlikely to have any common factors with the bucket size.
Why large primes. Wouldn't 2 and 3 do?
When computing hash codes for composite objects it's common to add the hash codes for the components. If too small values are used in a hash set with a large number of buckets there's a risk of ending up with an uneven distribution of objects.
Do collisions matter? Booleans just have two different values anyway?
Maps can contain booleans together with other objects. Also, as pointed out by Drunix, a common way to create hash functions of composite objects is to reuse the subcomponents hash code implementations in which case it's good to return large primes.
Related questions:
Read full article from java - Boolean.hashCode() - Stack Overflow

data structures - Difference between PriorityQueue and TreeSet in Java? - Stack Overflow



When you want a queue, use a PriorityQueue. When you want a Set, use a TreeSet. A TreeSet has unique elements, and doesn't offer the API of a Queue. A Queue doesn't offer the API of a Set, and allows multiple equal elements.

http://stackoverflow.com/questions/3524862/when-should-i-use-a-treemap-over-a-priorityqueue-and-vice-versa
Generally speaking, it is less work to track only the minimum element, using a heap.
A tree is more organized, and it requires more computation to maintain that organization. But if you need to access any key, and not just the minimum, a heap will not suffice, and the extra overhead of the tree is justified.
Read full article from data structures - Difference between PriorityQueue and TreeSet in Java? - Stack Overflow

What is PriorityQueue or priority queue data structure in Java with Example - Tutorial



PriorityQueue is an unbounded Queue implementation in Java, which is based on priority heap. PriorityQueue allows you to keep elements in a particular order, according to there natural order or custom order defined by Comparator interface in Java. Head of priority queue data structure will always contain least element with respect to specified ordering. For example, in this post, we will create a PriorityQueue of Items, which are ordered based upon there price, this will allow us to process Items, starting from lowest price. Priority queue is also very useful in implementing Dijkstra algorithm in Java. You can use to PriorityQueue to keep unsettled nodes for processing. One of the key thing to remember about PriorityQueue in Java is that it's Iterator doesn't guarantee any order, if you want to traverse in ordered fashion, better use Arrays.sort(pq.toArray()) method. PriorityQueue is also not synchronized, which means can not be shared safely between multiple threads, instead it's concurrent counterpart PriorityBlockingQueue is thread-safe and should be used in multithreaded environment. Priority queue provides O(log(n)) time performance for common enqueing and dequeing methods e.g. offer(), poll() and add(), but constant time for retrieval methods e.g. peek() and element().

1) PriorityQueue is not synchronized, if thread-safety is requirement use BlockingPriorityQueue.
2) Queue retrieval methods like poll(), peek() and element() access head of Queue, which keeps least element according to specified ordering.

3) Iterator returned by PriorityQueue doesn't offer any ordering traversal guarantee.
4) PriorityQueue doesn't allow null elements, if you try to add null, it will throw java.lang.NullPointerException.

That's all on what is PriorityQueue in Java and How to use them. It's an special class, which can be used in special scenarios, where you need to consume Orders in a particular order, remember BlockingQueue maintains insertion order, but if want to maintain a custom order, PriorityQueue or BlockingPriorityQueue is right collection to use. TreeSet also provides similar functionality, but doesn't have one short retrieval cum removal method e.g. poll().

Read full article from What is PriorityQueue or priority queue data structure in Java with Example - Tutorial

How to do deep cloning using in memory serialization in java - How To Do In Java



that easiest way of deep cloning (with some performance overhead) is Serialization. It involves serializing the object to bytes and from bytes to object again.

 public SerializableClass deepCopy() throws Exception
    {
        //Serialization of object
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(this);
 
        //De-serialization of object
        ByteArrayInputStream bis = new   ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream in = new ObjectInputStream(bis);
        SerializableClass copied = (SerializableClass) in.readObject();
 
        //Verify that object is not corrupt
 
        //validateNameParts(fName);
        //validateNameParts(lName);
 
        return copied;
    }
Read full article from How to do deep cloning using in memory serialization in java - How To Do In Java

Mark S. Kolich - Remember to Close Your Streams When Using Java's Runtime.getRuntime().exec()



That said, the undocumented proper way of handing a Process object and its corresponding I/O streams is to wrap the exec() call in a try-finally block, closing the STDOUT, STDIN, and STDERR streams when you’re done with the Process object. The abstract class java.lang.Process exposes these three streams to you via getOutputStream(), getInputStream() andgetErrorStream() which you must explicitly close.
Process p = null;
try {
  p = Runtime.getRuntime().exec(...);
  // Do something with p.
} finally {
  if(p != null) {
    closeQuietly(p.getOutputStream());
    closeQuietly(p.getInputStream());
    closeQuietly(p.getErrorStream());
  }
}

Read full article from Mark S. Kolich - Remember to Close Your Streams When Using Java's Runtime.getRuntime().exec()

Detecting process exit in Java | adrian's blog



It would be very nice if the Process class would implement the Observable design pattern in some way. But it doesn’t and on this we will base our workaround creation.
Process contains a useful method for us, waitFor, that pauses the current thread execution until the given subprocess is finished. So, we will create a thread that will be suspended until the given subprocess is finished. Then we will fire the listeners to notify that the process has finished its execution.

public void run() {
        try {
            // wait for the process to finish
            process.waitFor();
            // invokes the listeners
            for (ProcessListener listener : listeners) {
                listener.processFinished(process);
            }
        } catch (InterruptedException e) {
        }
    }

processExitDetector = new ProcessExitDetector(subprocess);
processExitDetector .addProcessListener(new ProcessListener() {
    public void processFinished(Process process) {
        System.out.println("The subprocess has finished.");
    }
});
Read full article from Detecting process exit in Java | adrian's blog

Labels

Algorithm (219) Lucene (130) LeetCode (97) Database (36) Data Structure (33) text mining (28) Solr (27) java (27) Mathematical Algorithm (26) Difficult Algorithm (25) Logic Thinking (23) Puzzles (23) Bit Algorithms (22) Math (21) List (20) Dynamic Programming (19) Linux (19) Tree (18) Machine Learning (15) EPI (11) Queue (11) Smart Algorithm (11) Operating System (9) Java Basic (8) Recursive Algorithm (8) Stack (8) Eclipse (7) Scala (7) Tika (7) J2EE (6) Monitoring (6) Trie (6) Concurrency (5) Geometry Algorithm (5) Greedy Algorithm (5) Mahout (5) MySQL (5) xpost (5) C (4) Interview (4) Vi (4) regular expression (4) to-do (4) C++ (3) Chrome (3) Divide and Conquer (3) Graph Algorithm (3) Permutation (3) Powershell (3) Random (3) Segment Tree (3) UIMA (3) Union-Find (3) Video (3) Virtualization (3) Windows (3) XML (3) Advanced Data Structure (2) Android (2) Bash (2) Classic Algorithm (2) Debugging (2) Design Pattern (2) Google (2) Hadoop (2) Java Collections (2) Markov Chains (2) Probabilities (2) Shell (2) Site (2) Web Development (2) Workplace (2) angularjs (2) .Net (1) Amazon Interview (1) Android Studio (1) Array (1) Boilerpipe (1) Book Notes (1) ChromeOS (1) Chromebook (1) Codility (1) Desgin (1) Design (1) Divide and Conqure (1) GAE (1) Google Interview (1) Great Stuff (1) Hash (1) High Tech Companies (1) Improving (1) LifeTips (1) Maven (1) Network (1) Performance (1) Programming (1) Resources (1) Sampling (1) Sed (1) Smart Thinking (1) Sort (1) Spark (1) Stanford NLP (1) System Design (1) Trove (1) VIP (1) tools (1)

Popular Posts