java.thread

  • Definition A thread is a single sequential flow of control within a program.
  • Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped. Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods
  • Thread are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started.finalize, getClass, hashCode, notify, notifyAll, wait, sleep, yield
  • What’s the difference between Thread and Runnable types? A Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main method. The Thread class provides a mechanism for the first thread to start-up other threads to run in parallel with it.

    The Runnable interface defines a type of class that can be run by a thread. The only method it requires is run, which makes the interface very easy to to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation.

  • What’s the difference between the methods sleep() and wait()The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
  • There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?If these classes are threads I’d consider notify() or notifyAll(). For regular classes you can use the Observer interface.
  • Why would you use a synchronized block vs. synchronized method?Synchronized blocks place locks for shorter periods than synchronized methods.
  • Starvation occurs when one or more threads in the program are blocked from gaining access to a resource and, as a result, cannot make progress.
  • A thread pool is a managed collection of threads that are available to perform tasks.
  • Deadlock the ultimate form of starvation, occurs when two or more threads are waiting on a condition that cannot be satisfied. Deadlock most often occurs when two (or more) threads are each waiting for the other(s) to do something.
  • Three versions of the wait method contained in the Object class: wait(): waits indefinitely for notification.

    wait(long timeout): waits for notification or until the timeout period has elapsed; timeout is measured in milliseconds.

    wait(long timeout, int nanos): waits for notification or until timeout milliseconds plus nanos nanoseconds have elapsed.

  • Shallow Copy is performed on object, then it is copied but its objects are not.
    public class Person implements Cloneable {
    public Person(String perName, String carMake) {
    name = perName;
    Car c = new Car(carMake);
    setCar(c);
    }
    
    private String name;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    
    private Car car;
    public Car getCar() {
    return car;
    }
    public void setCar (Car c) {
    car = c;
    }
    
    public Object clone() {
    try {
    return super.clone();
    } catch (CloneNotSupportedException cnse) {
    cnse.printStackTrace();
    } // TRY - CATCH
    return null;
    }
    }
    
    public class Car {
    
    public Car (String carMake) {
    make = carMake;
    }
    
    private String make;
    public String getMake() {
    return make;
    }
    public void setMake(String nam) {
    make = nam;
    }
    }
    
    public class ShallowCopyTest {
    
    public static void main(String[] args) {
    Person p1 = new Person("Krishna", "Nissan");
    System.out.println("Orignial :: Person name = "
    + p1.getName()
    + "tt Car Make = " + p1.getCar().getMake());
    
    Person p2 = (Person) p1.clone();
    System.out.println("Clone (Before update) :: Person name = "
    + p2.getName()
    + "tt Car Make = " + p2.getCar().getMake());
    
    p2.setName("Krishna 11");
    System.out.println("Clone (After Person name update)"
    + " :: Person name = " + p2.getName()
    + "tt Car Make = " + p2.getCar().getMake());
    
    p2.getCar().setMake("Honda");
    System.out.println("Clone (After clone is modified)"
    + " :: Person name = " + p2.getName()
    + "tt Car Make = " + p2.getCar().getMake());
    
    System.out.println("Original :: Person name = "
    + p1.getName()
    + "tt Car Make = " + p1.getCar().getMake());
    }
    }
    
    -----------------------------------
    Output::
    
    
    Orignial ::
    Person name = Krishna    Car Make = Nissan
    Clone (Before Change) ::
    Person name = Krishna      Car Make = Nissan
    Clone (After Person name update) ::
    Person name = Krishna 11     Car Make = Nissan
    Clone (After Person name & Car make update) ::
    Person name = Krishna 11    Car Make = Honda
    Original (After clone update on original) ::
    Person name = Krishna         Car Make = Honda
    
  • Deep Copy occurs when an object is copied along with teh objects to which refers
    public class Person implements Cloneable {
    
    public Person(String perName, String carMake) {
    name = perName;
    Car c = new Car(carMake);
    setCar(c);
    }
    
    private String name;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    
    private Car car;
    public Car getCar() {
    return car;
    }
    public void setCar (Car c) {
    car = c;
    }
    
    public Object clone() {
    Person p = new Person(name, car.getMake());
    return p;
    }
    }
    
    public class Car {
    
    public Car (String carMake) {
    make = carMake;
    }
    
    private String make;
    public String getMake() {
    return make;
    }
    public void setMake(String nam) {
    make = nam;
    }
    }
    
    public class DeepCopyTest {
    
    public static void main(String[] args) {
    Person p1 = new Person("Krishna", "Nissan");
    System.out.println("Orignial :: Person name = "
    + p1.getName()
    + "tt Car Make = " + p1.getCar().getMake());
    
    Person p2 = (Person) p1.clone();
    System.out.println("Clone (Before Change) :: Person name = "
    + p2.getName()
    + "tt Car Make = " + p2.getCar().getMake());
    
    p2.setName("Krishna 11");
    System.out.println("Clone (After Person name update)"
    + " :: Person name = " + p2.getName()
    + "tt Car Make = " + p2.getCar().getMake());
    
    p2.getCar().setMake("Honda");
    System.out.println("Clone (After Person name & Car make update)"
    + " :: Person name = " + p2.getName()
    + "tt Car Make = " + p2.getCar().getMake());
    
    System.out.println("Original (After clone update on original)"
    + " :: Person name = " + p1.getName()
    + "tt Car Make = " + p1.getCar().getMake());
    }
    }
    
    -----------------------------------
    Output::
    
    
    Orignial ::
    Person name = Krishna    Car Make = Nissan
    Clone (Before Change) ::
    Person name = Krishna    Car Make = Nissan
    Clone (After Person name update) ::
    Person name = Krishna 11  Car Make = Nissan
    Clone (After Person name & Car make update) ::
    Person name = Krishna 11    Car Make = Honda
    Original (After clone update on original) ::
    Person name = Krishna    Car Make = Nissan
    
  • Other Tips:
    1. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will be blocked until the object is unlocked.
    2. The Object class provides a collection of methods ? wait, notify, and notifyAll ? to help threads wait for a condition and to notify other threads when that condition changes.
    3. Task scheduling framework: The Executor framework is a collection of interfaces and classes for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies. Implementations are provided that allow tasks to be executed within the submitting thread, in a single background thread (as with events in Swing), in a newly created thread, or in a thread pool; create implementations of Executor supporting arbitrary execution policies. The built-in implementations offer configurable policies, such as queue-length limits and saturation policy, that can improve the stability of applications by preventing runaway resource consumption.
    4. Locks: While locking is built into the Java programming language via the synchronized keyword, there are a number of inconvenient limitations to built-in monitor locks. The java.util.concurrent.locks package provides a high-performance lock implementation with the same memory semantics as synchronization; it also supports specifying a timeout when attempting to acquire a lock, multiple condition variables per lock, non-lexically scoped locks, and support for interrupting threads waiting to acquire a lock.
    5. Synchronizers: General-purpose synchronization classes, including semaphores, mutexes, barriers, latches, and exchangers, facilitate coordination between threads.
    6. Concurrent collections: The Java Collections Framework (discussed in Collections, contains several concurrent collections, including the Queue and BlockingQueue interfaces, and high-performance, concurrent implementations of Map, List, and Queue.
    7. Atomic variables: Classes for atomically manipulating single variables (primitive types or references) provide high-performance atomic arithmetic and compare-and-set methods. The atomic variable implementations in java.util.concurrent.atomic offer higher performance than would be available by using synchronization (on most platforms), making them useful for implementing high-performance concurrent algorithms as well as conveniently implementing counters and sequence number generators.
    8. Nanosecond-granularity timing: The System.nanoTime method enables access to a nanosecond-granularity time source for making relative time measurements; and methods that accept timeouts, such as BlockingQueue.offer, BlockingQueue.poll, Lock.tryLock, Condition.await, and Thread.sleep, can take timeout values in nanoseconds. The actual precision of System.nanoTime is platform-dependent.

Definition A thread is a single sequential flow of control within a program. Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped. Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can…

Leave a Reply

Your email address will not be published. Required fields are marked *