Reasons for multithreading:

  • I/O bound process
  • User Interface thread
  • Take advantage of multi-core CPU

How to make an Java object thread-safe

  • Make the object stateless, it makes no external references that might need synchronized access, and all static variables are final immutable.
  • Make shared variables concurrent.
  • Proper use of locking synchronization

An object is thread-safe when it is called by multiple threads at the same time and it is still in a valid state.

Difference between thread-safe and concurrency:

Thread-safe implies locking entire object, concurrent implies read operations do not lock object.
For example, concurrent access to hash map allow concurrent access to different partitions.

Creating Thread

class MyThread extends Thread {
	@Override
	public void run();
}
new MyThread().start();

new Thread(new Runnable()).start();