madhusudanareddysingana.files.wordpress.com  · web viewadv of threads: achieve parallelism in...

18
Adv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response time might effect. To do tasks parallel i.e jogging with listening to music http://javarevisited.blogspot.com/2017/03/why-we-use-threads-in- java.html daemon threads are low prioritized than user threads.JVM will closes them soon once user threads completed their execution. For user threads it won’t close until all user threads completes their execution.

Upload: phamthuan

Post on 07-May-2018

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

Adv of threads:

Achieve parallelism in java.

In multi core cpus HW is high end and if you use sequential execution then response time might effect.

To do tasks parallel i.e jogging with listening to music

http://javarevisited.blogspot.com/2017/03/why-we-use-threads-in-java.html

daemon threads are low prioritized than user threads.JVM will closes them soon once user threads completed their execution.

For user threads it won’t close until all user threads completes their execution.

Page 2: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

http://www.java67.com/2016/06/difference-between-daemon-vs-user-thread-in-java.html

http://stackoverflow.com/questions/24649842/scheduleatfixedrate-vs-schedulewithfixeddelay

Timer vs ExecutorServicehttp://stackoverflow.com/questions/409932/java-timer-vs-executorservice?rq=1

236down voteaccepted

According to Java Concurrency in Practice: Timer can be sensitive to changes in the system

clock, ScheduledThreadPoolExecutor isn't. Timer has only one execution thread, so long-running task can delay other

tasks. ScheduledThreadPoolExecutor can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing ThreadFactory).

Runtime exceptions thrown in TimerTask kill that one thread, thus making Timer dead :-( ... i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want (by overriding afterExecute method from ThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run.

If you can use ScheduledThreadExecutor instead of Timer, do so.

should-i-synchronize-constructor:

Page 3: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

As per the JLS#8.8.3There is no practical need for a constructor to be synchronized, because it would lock the object under construction, which is normally not made available to other threads until all constructors for the object have completed their work.So that implies the reference is being synchronized prior to be accessible.

Since you are correctly synchronizing, it would be said writes that occur in the constructor would happen-before the object is published, so long as the synchronization is consistent on said fieldIn your case since getX() and setX() are both synchronized, the synchronization is consistent and you do not need to sync in the constructor.

Now, would you ever need to synchronize(this) on the constructor? No, as the JLS mentions it is implicitly synchronizing without you knowing about it.

http://stackoverflow.com/questions/574240/is-there-an-advantage-to-use-a-synchronized-method-instead-of-a-synchronized-blo?rq=1

Can any one tell me the advantage of synchronized method over synchronized block with an example?Thanks.

There is not a clear advantage of using synchronized method over block.

Perhaps the only one ( but I wouldn't call it advantage ) is you don't need to include the object reference this.Method:

public synchronized void method() { // blocks "this" from here.... ... ... ...} // to hereBlock:

public void method() { synchronized( this ) { // blocks "this" from here .... .... .... .... } // to here...}See? No advantage at all.

Blocks do have advantages over methods, most of all in flexibility because you can use other object as lock whereas syncing the method would lock the complete class.Compare:

// locks the whole object...

Page 4: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

private synchronized void someInputRelatedWork() { ... }private synchronized void someOutputRelatedWork() { ... }Vs.

// Using specific locksObject inputLock = new Object();Object outputLock = new Object();

private void someInputRelatedWork() { synchronize(inputLock) { ... } }private void someOutputRelatedWork() { synchronize(outputLock) { ... }}Also if the method grows you can still keep the synchronized section separated:

private void method() { ... code here ... code here ... code here synchronized( lock ) { ... very few lines of code here } ... code here ... code here ... code here ... code here}

http://stackoverflow.com/questions/19000324/advantage-of-using-executors-newsinglethreadexecutor

Writing literally

Executors.newSingleThreadExecutor().submit(job);is pointless: it's just the wrong way to do

new Thread(job).start();As opposed to the latter, the former will leave the thread hanging on until the Executor Service is finalized.

The advantage of using an Executor Service comes about when you keep it around as an instance/class variable and reuse it for many submitted tasks. The Executor Service must be properly shutdown when you are done with it.

Page 5: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

More generally, the difference between submitting tasks to an executor service and just running the tasks is in the achieved concurrency. Whether that results in any advantage is highly specific to the job being submitted: it may also be useless or even broken (causing data races, deadlocks, etc.).

Creating a memory leak:

Here's a good way to create a true memory leak (objects inaccessible by running code but still stored in memory) in pure Java:

1. The application creates a long-running thread (or use a thread pool to leak even faster).

2. The thread loads a class via an (optionally custom) ClassLoader.

3. The class allocates a large chunk of memory (e.g. new byte[1000000]), stores a strong reference to it in a static field, and then stores a reference to itself in a ThreadLocal. Allocating the extra memory is optional (leaking the Class instance is enough), but it will make the leak work that much faster.

4. The thread clears all references to the custom class or the ClassLoader it was loaded from.

5. Repeat.This works because the ThreadLocal keeps a reference to the object, which keeps a reference to its Class, which in turn keeps a reference to its ClassLoader. The ClassLoader, in turn, keeps a reference to all the Classes it has loaded. It gets worse because in many JVM implementations Classes and ClassLoaders are allocated straight into permgen and are never GC'd at all.

A variation on this pattern is why application containers (like Tomcat) can leak memory like a sieve if you frequently redeploy applications that happen to use ThreadLocals in any way. (Since the application container uses Threads as described, and each time you redeploy the application a new ClassLoader is used.)

Update: Since lots of people keep asking for it, here's some example code that shows this behavior in action.

Nice explanation on Thread vs Runnable:

http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread?rq=1

join in threadshttp://javarevisited.blogspot.com/2013/02/how-to-join-multiple-threads-in-java-example-tutorial.html

Page 6: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

The Java volatile keyword is used to mark a Java variable as "being stored in main memory". More precisely that means, that every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.

Volatile and synchronized:http://tutorials.jenkov.com/java-concurrency/volatile.html

stoping a threadhttp://www.java67.com/2015/07/how-to-stop-thread-in-java-example.html

wait and sleep:http://stackoverflow.com/questions/1036754/difference-between-wait-and-sleep

serializable vs extrenilazablehttp://javarevisited.blogspot.sg/2012/01/serializable-externalizable-in-java.html

Coming back to yield(), it's little different than wait() and sleep(), it just releases the CPU hold by Thread to give another thread an opportunity to run though it's not guaranteed who will get the CPU. It totally depends upon thread scheduler and it's even possible that the thread which calls the yield() method gets the CPU again. Hence, it's not reliable to depend upon yield() method, it's just on best effort basis.

Read more: http://javarevisited.blogspot.com/2011/12/difference-between-wait-sleep-yield.html#ixzz4hqpIrgYY

Difference between yield and sleep in JavaThe major difference between yield and sleep in Java is that yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee   that  current thread will pause or stop but it guarantee that CPU will be relinquished by current Thread as a result of a call to Thread.yield() method in java. See   Java Concurrency in Practice  for more details. 

Page 7: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

Sleep method in Java has two variants one which takes millisecond as sleeping time while other which takes both mill and nanosecond for sleeping duration.

sleep(long millis)

orsleep(long millis,int nanos)

Read more: http://javarevisited.blogspot.com/2011/12/difference-between-wait-sleep-yield.html#ixzz4hqqFY7zZ

10 points about Thread sleep() method in JavaI have listed down some important and worth to remember points about Sleep() method of Thread Class in Java:

1) Thread.sleep() method is used to pause 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.

Page 8: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

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".

That’s all on Sleep method in Java. We have seen the difference between sleep and wait along with sleep and yield in Java. In Summary, just keep in mind that both sleep() and yield() operate on the current thread.

Read more: http://javarevisited.blogspot.com/2011/12/difference-between-wait-s nstead of   synchronized   variable in Java, you can have java   volatile   variable, which will instruct JVM threads to read the value of the volatile variable from main   memory   and don’t cache it locally.   Block synchronization in Java is preferred over method synchronization in Java   because by using block synchronization, you only need to lock the critical section of code instead of the whole method. Since synchronization in Java comes with the cost of performance, we need to synchronize only part of the code which absolutely needs to be synchronized.

Read more:   http://javarevisited.blogspot.com/2011/04/synchronization-in- java-synchronized.html#ixzz4hr3H9eDIleep-yield.html#ixzz4hqqZxcHc

Static ENUM vs NON-Static ENum JAVA

87down voteaccepted

All enums are effectively static. If you have a nested enum, it is much the same as a static class.All classes are lazily loaded (enums or otherwise) however when they are loaded they are loaded all at once. i.e. you can't have a few constants loaded but not others (except in the middle of class initialization)

Java allows certain modifiers to be implicit to avoid having to declare them all the time. This means that adding a modifier doesn't always do anything other be a longer way of writing the same thing.

Default modifiers for

class field/method/nested class - package local, non-final, non-static

enum and nested enum - package local, final and static

interface field - public static finalinterface method - public abstract

Page 9: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

nested class in an interface - public static, non-finalNote: while static is optional for an enum it is always static. However, final cannot be set for an enum even though it is always notionally final (Technically you can have subclasses with overridden implementations for constants)EDIT: The only place you need to use static with enum is with import static of an enum's value. Thank you @man910

https://stackoverflow.com/questions/6367885/difference-between-synchronizing-a-static-method-and-a-non-static-method

next>> <<prev

Priority of a Thread (Thread Priority):Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

3 constants defiend in Thread class:

1. public static int MIN_PRIORITY2. public static int NORM_PRIORITY3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Example of priority of a Thread:1. class TestMultiPriority1 extends Thread{  2.  public void run(){  3.    System.out.println("running thread name is:"+Thread.currentThread().getName());  4.    System.out.println("running thread priority is:

"+Thread.currentThread().getPriority());  5.   6.   }  7.  public static void main(String args[]){  8.   TestMultiPriority1 m1=new TestMultiPriority1();  9.   TestMultiPriority1 m2=new TestMultiPriority1();  10.   m1.setPriority(Thread.MIN_PRIORITY);  

Page 10: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

11.   m2.setPriority(Thread.MAX_PRIORITY);  12.   m1.start();  13.   m2.start();  14.    15.  }  16. }     

Test it Now

Output:running thread name is:Thread-0

running thread priority is:10

running thread name is:Thread-1

running thread priority is:1

Next TopicDaemon Thread

Page 11: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

Java Shutdown HookThe shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. Performing clean resource means closing log file, sending some alerts or something else. So if you want to execute some code before JVM shuts down, use shutdown hook.

When does the JVM shut down?The JVM shuts down when:

o user presses ctrl+c on the command prompto System.exit(int) method is invokedo user logoffo user shutdown etc.

The addShutdownHook(Thread hook) method

The addShutdownHook() method of Runtime class is used to register the thread with the Virtual Machine. Syntax:

1. public void addShutdownHook(Thread hook){}  

The object of Runtime class can be obtained by calling the static factory method getRuntime(). For example:

Runtime r = Runtime.getRuntime();

Factory method

The method that returns the instance of a class is known as factory method.

Simple example of Shutdown Hook1. class MyThread extends Thread{  2.     public void run(){  

Page 12: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

3.         System.out.println("shut down hook task completed..");  4.     }  5. }  6.   7. public class TestShutdown1{  8. public static void main(String[] args)throws Exception {  9.   10. Runtime r=Runtime.getRuntime();  11. r.addShutdownHook(new MyThread());  12.       13. System.out.println("Now main sleeping... press ctrl+c to exit");  14. try{Thread.sleep(3000);}catch (Exception e) {}  15. }  16. }  

Output:Now main sleeping... press ctrl+c to exit

shut down hook task completed..

Note: The shutdown sequence can be stopped by invoking the halt(int) method of Runtime class.

Same example of Shutdown Hook by annonymous class:1. public class TestShutdown2{  2. public static void main(String[] args)throws Exception {  3.   4. Runtime r=Runtime.getRuntime();  5.   6. r.addShutdownHook(new Thread(){  7. public void run(){  8.     System.out.println("shut down hook task completed..");  9.     }  10. }  11. );  12.       13. System.out.println("Now main sleeping... press ctrl+c to exit");  14. try{Thread.sleep(3000);}catch (Exception e) {}  

Page 14: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

JavaTpoint offers Summer Internship Training on Java, PHP, .Net, Hadoop, Data Analytics, R Programming, SAP, Android, Python, Oracle, Seleninum, Linux, C++ and many more technologies in Delhi/NCR, India. For more visit  training.javatp

finalize() methodThe finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:

1. protected void finalize(){}  

Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

gc() methodThe gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

1. public static void gc(){}  

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection in java1. public class TestGarbage1{  

Page 15: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

2.  public void finalize(){System.out.println("object is garbage collected");}  3.  public static void main(String args[]){  4.   TestGarbage1 s1=new TestGarbage1();  5.   TestGarbage1 s2=new TestGarbage1();  6.   s1=null;  7.   s2=null;  8.   System.gc();  9.  }  10. }  

Page 16: madhusudanareddysingana.files.wordpress.com  · Web viewAdv of threads: Achieve parallelism in java. In multi core cpus HW is high end and if you use sequential execution then response

ow can an object be unreferenced?There are many ways:

o By nulling the referenceo By assigning a reference to anothero By annonymous object etc.

1) By nulling a reference:1. Employee e=new Employee();  2. e=null;  

2) By assigning a reference to another:1. Employee e1=new Employee();  2. Employee e2=new Employee();  3. e1=e2;//now the first object referred by e1 is available for garbage collection  

3) By annonymous object:1. new Employee();  

https://www.javatpoint.com/java-runtime-class