Wednesday, April 20, 2016

Java Threads Cheat Sheet


wait & notify
  • wait() - always in a condition loop
  • notify() - wake up a random thread
  • notifyAll() - wake up all waiting threads
  • yield() - give up the processor (pass your turn)
  • join() - blocker method - wait for a thread to finish




Runnable vs Thread vs Callable
  • Thread - can be extended
  • Runnable - interface , allows extending another class , works with executors
  • Callable - like runnable but returns result and can throw a checked exception
  • start() - spawns a new thread and calls run
  • run() - just calls the function with the current thread




Executors and Future
  • Executor - executes submitted Runnable tasks
  • ExecutorService - An Executor with termination and that can produce a Future for tracking progress of one or more asynchronous tasks.

    • shutdown() - Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted
    • shutdownNow() Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
    • submit(Callable<T> task) Submits a value-returning task for execution and returns a Future representing the pending results of the task.

  • ScheduledExecutorService - An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.
  • Future - represents the result of an asynchronous computation
  • FutureTask - base implementation of Future




Thread conditions
  • Deadlock - two or more tasks never make progress because each is waiting for some resource held by another process
    • Mutual exclusion. There must be some resource that can't be shared between processes.
    • Hold and wait. Some process must be holding one resource while waiting for another.
    • No preemption. Only the process holding a resource can release it.
    • Circular wait. There must be some cycle of waiting processes P1, P2, ..., Pn such that each process Pi is waiting for a resource held by the next process in the cycle. (Note that this implies hold-and-wait.)
  • Livelock - threads react to each other and don't progress
  • Race condition - A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. 
  • Starvation - not enough cpu time because of other greedy threads




Data Structures for multithreading
  • Lock - interface implementations provide more extensive locking operations than can be obtained using synchronized methods and statements
  • ReentrantLock - monitor with fairness feature
  • ReadWriteLock - interface - has two locks for reading and writing, allows multiple reads
  • ReentrantReadWriteLock - read write lock with fairness
  • CyclicBarrier - allows a set of threads to all wait for each other to reach a common barrier point, can be re-used after the waiting threads are released, can call a runnable when the barrier is tripped
  • CountdownLatch -allows one or more threads to wait until a set of operations being performed in other threads completes
  • Semaphore - counting semaphore, used to restrict the number of threads than can access some resource
  • Mutex - binary sempahore
  • Monitor - implicit lock each object has
  • BlockingQueue - Thread safe queue
  • ConcurrentHashMap - thread safe hashtable


Misc
  • ThreadLocal - thread-local variables
  • DeamonThread - background threads ignored by the JVM in shutdown
  • volatile - The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory"; Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

Tuesday, February 16, 2016

10 things to do before your code review

Code reviews are important , they make you take another look at you code before you submit it.
After going through a lot of code reviews here are 10 tips to make sure you prepare properly.

1. Clean up your code
Remove those commented out code sections, indent your code properly.
Clean code displays preparation and respect for the reviewer, it also makes you go over all the files you changed which can help you find todos you forgot.

2. Refactoring
Check for duplicate code you can extract into a function, Does your function name really represent what it does? Maybe it's too smart and needs to be divided into several functions.

3.Security
Rethink you code from a security perspective, did you sanitize user inputs? Does you code execute shell scripts? Under what permissions?
If your code writes to the database make sure you encode the input and use prepared statements.
Does the data need to be encrypted?

4. Design
Could the code have reused existing functionality?
What design patterns are used in you code?
Is the code in the correct packages?

5. Comments
Your function and class names may be self explanatory but there is no substitute for code comments. Chances are you won't remember in a week why you used that function and the developer after you sure won't. Looking at the code can tell you how the program works but comments can tell you why it works.

6. Write down the comments from your peers
You won't remember what they said once the meeting is over, writing down comments shows that you are able to accept criticism.

7. Plan for at least 60 minutes but not more
If there is a lot of code to go over split the review into another meeting.

8. Focus on what matters
Nobody is interested in looking at the automatically generated getters and setters in you code. Show the main functionality you've added , focus on what needs to be tested after your changes.

9. Performance
Keep performance in mind, does you code need to adhere to an SLA? if so , provide proof that this has been tested.
Don't call the server/database twice if you can do it once , it may not seem like a big deal but it adds up. Look for loops that contain network calls or database queries.
Does you code close connections properly?
Do you use timeouts? How do you know you picked the correct timeout? What happens if the timeout is reached?
Do you use caching? when are items invalidated?

10. Error handling
How did you handle exceptions in you code? from incorrect user data to network and database failures, Make sure your code can recover and log the exceptions.