Что такое findslide.org?

FindSlide.org - это сайт презентаций, докладов, шаблонов в формате PowerPoint.


Для правообладателей

Обратная связь

Email: Нажмите что бы посмотреть 

Яндекс.Метрика

Презентация на тему Thread execute sequence

Difference between start and rundifference between start() and run() method in Thread is that start creates new thread while run doesn't create any thread and simply execute in current thread like a normal method call.
Thread execute sequenceThread thread1 = createThread( Difference between start and rundifference between start() and run() method in Thread Benefit of Producer Consumer PatternProducer Consumer Pattern1) Producer Consumer Pattern simple development. Thread-Safe Code/* * Non Thread-Safe Class in Java */public class Counter {      private int Important points about Thread-Safety in JavaImmutable objects are by default thread-safe because Blocking methodsExamples of blocking methods in Java:public class BlcokingCallTest {    public static Blocking methods1) Always let separate worker thread handles time consuming operations e.g. Thread sleep()1) Thread.sleep() method is used to pause the execution, relinquish the The Volatile variable/** * Java program to demonstrate where to use Volatile If we do not make the _instance variable volatile than the Thread which Daemon threads1. Any thread created by main thread, which runs main method
Слайды презентации

Слайд 2 Difference between start and run
difference between start() and

Difference between start and rundifference between start() and run() method in

run() method in Thread is that start creates new

thread while run doesn't create any thread and simply execute in current thread like a normal method call.

Слайд 3 Benefit of Producer Consumer Pattern
Producer Consumer Pattern
1) Producer

Benefit of Producer Consumer PatternProducer Consumer Pattern1) Producer Consumer Pattern simple

Consumer Pattern simple development. you can Code Producer and

Consumer independently and Concurrently, they just need to know shared object.

2) Producer doesn't need to know about who is consumer or how many consumers are there. Same is true with Consumer.

3) Producer and Consumer can work with different speed. There is no risk of Consumer consuming half-baked item.
In fact by monitoring consumer speed one can introduce more consumer for better utilization.

4) Separating producer and Consumer functionality result in more clean, readable and manageable code.


Read more: http://javarevisited.blogspot.com/2012/02/producer-consumer-design-pattern-with.html#ixzz4dHNL8sPU

Слайд 4 Thread-Safe Code
/*
 * Non Thread-Safe Class in Java
 */
public class

Thread-Safe Code/* * Non Thread-Safe Class in Java */public class Counter {      private

Counter {
  
    private int count;
  
    /*
     * This method

is not thread-safe because ++ is not an atomic operation
     */
    public int getCount(){
        return count++;
    }
}


Read more: http://javarevisited.blogspot.com/2012/01/how-to-write-thread-safe-code-in-java.html#ixzz4dHpKQDfk

A thread-safe version of Counter class in Java:

/*
 * Thread-Safe Example in Java
 */
public class Counter {
  
    private int count;
    AtomicInteger atomicCount = new AtomicInteger( 0 );

  
    /*
     * This method thread-safe now because of locking and synchornization
     */
    public synchronized int getCount(){
        return count++;
    }
  
    /*
     * This method is thread-safe because count is incremented atomically
     */
    public int getCountAtomically(){
        return atomicCount.incrementAndGet();
    }
}


Слайд 5 Important points about Thread-Safety in Java
Immutable objects are

Important points about Thread-Safety in JavaImmutable objects are by default thread-safe

by default thread-safe because there state can not be

modified once created. Since String is immutable in Java, its inherently thread-safe.

2) Read only or final variables in Java are also thread-safe in Java.

3) Locking is one way of achieving thread-safety in Java.

4) Static variables if not synchronized properly becomes major cause of thread-safety issues.

5) Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String etc.

6) Atomic operations in Java are thread-safe e.g. reading a 32 bit int from memory because its an atomic operation it can't interleave with other thread.

7) local variables are also thread-safe because each thread has there own copy and using local variables is good way to writing thread-safe code in Java.

8) In order to avoid thread-safety issue minimize sharing of objects between multiple thread.

9) Volatile keyword in Java can also be used to instruct thread not to cache variables and read from main memory and can also instruct JVM not to reorder or optimize code from threading perspective.

Слайд 6 Blocking methods
Examples of blocking methods in Java:
public class

Blocking methodsExamples of blocking methods in Java:public class BlcokingCallTest {    public

BlcokingCallTest {

    public static void main(String args[]) throws FileNotFoundException,

IOException  {
      System.out.println("Calling blocking method in Java");
      int input = System.in.read();
      System.out.println("Blocking method is finished");
    }  
}

1) InputStream.read() which blocks until input data is available, an exception is thrown or end of Stream is detected.
2) ServerSocket.accept() which listens for incoming socket connection in Java and blocks until a connection is made.
3) InvokeAndWait() wait until code is executed from Event Dispatcher thread.


Read more: http://javarevisited.blogspot.com/2012/02/what-is-blocking-methods-in-java-and.html#ixzz4dHxaEmxu


Слайд 7 Blocking methods
1) Always let separate worker thread handles

Blocking methods1) Always let separate worker thread handles time consuming operations

time consuming operations e.g. reading and writing to file,

database or
socket.

2) Use timeout while calling blocking method. so if your blocking call doesn't return in specified time period, consider
aborting it and returning back but again this depends upon scenario. if you are using Executor Framework for managing
your worker threads, which is by the way recommended way than you can use Future object whose get() methods support timeout, but ensure that you properly terminate a blocking call.

3) Extension of first practices, don't call blocking methods on keyPressed() or paint() method which are supposed to
return as quickly as possible.

4) Use call-back functions to process result of a blocking call.

5) If you are writing GUI application may be in Swing never call blocking method in Event dispatcher thread or
in the event handler. for example if you are reading a file or opening a network connection when a button is clicked
don't do that on actionPerformed() method, instead just create another worker thread to do that job and return from
actionPerformed(). this will keep your GUI responsive, but again it depends upon design if the operation is something which requires user to wait than consider using invokeAndWait() for synchronous update.

Best practices while calling blocking method in Java:


Слайд 8 Thread sleep()
1) Thread.sleep() method is used to pause

Thread sleep()1) Thread.sleep() method is used to pause the execution, relinquish

the execution, relinquish the CPU and return it to

thread scheduler.

2) Thread.The sleep() method is a static method and always puts the current thread to sleep.

3) Java has two variants of sleep method in Thread class one with one argument which takes milliseconds as the duration of sleep and another method with two arguments one is millisecond and other is the nanosecond.

4) Unlike wait() method in Java, sleep() method of Thread class doesn't relinquish the lock it has acquired.

5) sleep() method throws Interrupted Exception if another thread interrupts a sleeping thread in java.

6) With sleep() in Java it's not guaranteed that when sleeping thread woke up it will definitely get CPU, instead it will go to Runnable state and fight for CPU with other thread.

7) There is a misconception about sleep method in Java that calling t.sleep() will put Thread "t" into sleeping state, that's not true because Thread.sleep method is a static method it always put the current thread into Sleeping state and not thread "t".

Слайд 9 The Volatile variable
/** * Java program to demonstrate

The Volatile variable/** * Java program to demonstrate where to use

where to use Volatile keyword in Java. * In

this example Singleton Instance is declared as volatile variable to ensure * every thread see updated value for _instance. * * @author Javin Paul */ public class Singleton{
private static volatile Singleton _instance; //volatile variable
public static Singleton getInstance() {
if(_instance == null) {
synchronized(Singleton.class) {
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}

Read more: http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html#ixzz4dMPEBp5Z

The volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory

If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of the first request comes.


Слайд 10 If we do not make the _instance variable volatile

If we do not make the _instance variable volatile than the Thread

than the Thread which is creating instance of Singleton

is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.

The Volatile variable

Java volatile keyword doesn't mean atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.


  • Имя файла: thread-execute-sequence.pptx
  • Количество просмотров: 137
  • Количество скачиваний: 0