JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Showing posts with label Java Multithreading Tutorial. Show all posts
Showing posts with label Java Multithreading Tutorial. Show all posts

Explain about CyclicBarrier in Java

1:28 AM
How to use CyclicBarrier in Java - Concurrency Tutorial This is the second part of my concurrency tutorial, in the first part, you have learned how to use CountDownLatch and in this part, you will learn how to use CyclicBarrier class in Java. CyclicBarrier is another concurrency utility introduced in Java 5 which is used when a number of threads (also known as parties) want to wait for each other at a common point, also known as the barrier before starting processing again. Its similar to CountDownLatch but instead of calling countDown() each thread calls await() and when last thread calls await() which signals that it has reached the barrier, all thread started processing again, also known as a barrier is broken. You can use CyclicBarrier wherever you want to use CountDownLatch, but the opposite is not possible because you can not reuse the latch once the count reaches to zero. Some of the common usages of CyclicBarrier is in writing a unit test for concurrent program, to simulate...

Explain about CountDowaLatch

1:18 AM
Explain about CountDowaLatch CountDowaLatch is a high-level synchronization utility which is used to prevent a particular thread to start processing until all threads are ready. This is achieved by a countdown. The thread, which needs to wait for starts with a counter, each thread them make the count down by 1 when they become ready, once the last thread call countDown() method, then the latch is broken and the thread waiting with counter starts running. CountDownLatch is a useful synchronizer and used heavily in multi-threaded testing. You can use this class to simulate truly concurrent behavior i.e. trying to access something at the same time once every thread is ready. Worth noting is that CountDownLatch starts with a fixed number of counts which cannot be changed later, though this restriction is re-mediated in Java 7 by introducing a similar but flexible concurrency utility called Phaser. There is another similar utility called CyclicBarrier, which can also be used in this si...

Producer Consumer problem Solution using BlockingQueue in Java Thread

1:14 AM
Producer Consumer Solution using BlockingQueue in Java Thread Producer Consumer problem is one of the classic multi-threading problems in computer science and the multi-threading world. It's tricky because it involves inter-thread communication, but it's important because most of the multi-threading problems fits into this category. There are many ways to solve producer consumer problem in Java e.g. you can solve this by using wait() and notify() method, as discussed here, or you can use the Semaphore to solve this problem. In this article, you will learn a third way to solve the producer-consumer problem by using the BlockingQueue in Java. It is arguably the simplest way to solve this problem in any programming language because blocking queue data structure not only provides storage but also provides flow control and thread-safety, which makes the code really simple. Brian Goetz has also explained this key class and pattern in his classic Java Concurrency in Practice book,...

Sleep vs yield in Java

1:11 AM
Sleep vs yield in Java Sleep and yield are two methods which are used to get CPU back from Thread to Thread Scheduler in java but they are completely different than each other. The major difference between Sleep vs yield is that sleep is more reliable than yield and it's advised to use sleep(1) instead of yield to relinquish CPU in multi-threaded Java application to give an opportunity to other threads to execute. In this Java tutorial, we will what are differences between yield and sleep in Java. But before seeing difference between sleep and Yield let's see some similarities between yield and sleep in Java Similarities between Sleep and yield in Java  Here are some common things between sleep and yield method in Java programming : 1) Both yield and sleep are declared on java.lang.Thread class. 2) Both sleep() and yield() are static methods and operate on current thread. It doesn't matter which thread's object you used to call this method, both these meth...

Explain wait(), notify() and notifyAll() in Java Thread?

1:08 AM
If you ask me one concept in Java which is so obvious yet most misunderstood, I would say the wait(), notify() and notifyAll() methods. They are quite obvious because they are the one of the three methods of total 9 methods from java.lang.Object but if you ask when to use the wait(), notify() and notfiyAll() in Java, not many Java developer can answer with surety. The number will go down dramatically if you ask them to solve the producer-consumer problem using wait() and notify(). Many will use if block instead of while loop, many others will get confused on which object they should call wait() and notify()method? Some of them even succeed in creating livelock, deadlock, and other multithreading issues. That's why it's become very important to know as much as possible about these three methods. In this article, I am going to share some practical tips and points about wait(), notify() and notifyAll() in Java. Two books, which helped me a lot while understanding this core c...

How to use Multiple Threads in Java with Example

1:06 AM
you need to first define the task which will be executed by those threads. In order to create those task, you can either use Runnable or Callable interface. If you are just learning Java chose Runnable, it's simpler one, but if you are familiar with Java multithreading and want to leverage additional features offered by Callable e.g. it can throw an exception and it can also return value, then go ahead and use Callable. Once you have task ready, you need to create an instance of Thread class. You can create as many instances as you want, but beware don't create too many Thread instances in Java because both JVM and Operating system has a limit on how many threads you can create in Java. Crossing that limit will result in java.lang.OutOfmemoryError: could not create a native thread. For the purpose of this example, creating just three threads are enough. Let's assume we create threads T1, T2, and T3. While creating we pass them an instance of your Task class, which extend...

Difference between Daemon Thread vs User Thread in Java with example?

1:01 AM
Difference between Daemon Thread vs User Thread in Java? A thread is used to perform parallel execution  in Jaa e.g. while rendering screen your program is also downloading the data from the internet in the background. There are two types of threads in Java, user thread and daemon thread, both of which can use to implement parallel processing in Java depending upon priority and importance of the task. The main difference between a user thread and a daemon thread is that your Java program will not finish execution until one of the user thread is live. JVM will wait for all active user threads to finish their execution before it shutdown itself. On the other hand, a daemon thread doesn't get that preference, JVM will exit and close the Java program even if there is a daemon thread running in the background. They are treated as low priority threads in Java, that's why they are more suitable for non-critical background jobs. In this article, we will learn some key difference be...

What is What is difference between wait and sleep in Java Thread?

12:56 AM
Wait vs sleep in Java ? Differences between wait and sleep method in Java multi-threading is one of the very old questions asked in Java interviews. Though both wait and sleep put thread on waiting state, they are completely different in terms of behavior and use cases. Thread.sleep(long millis) is meant for introducing pause, releasing CPU and giving another thread an opportunity to execute while wait is used for inter thread communication in Java. These methods are defined in java.lang.Object class and available to every object in Java. It is based upon object lock, if you remember every object in Java has implicit lock, also known as monitor. When a thread enter into a synchronized method it acquired the lock which is used to protect the critical reason e.g. it acquired lock on current object if it is going inside an instance synchronized method and lock object on class literal if its entering into a static synchronized method. By using wait() and notify() method two threads can c...

Explain bout wait() and join method in Java thread

12:50 AM
Though both wait() and join() methods are used to pause the current thread and have a lot of similarities they have different purposes. One of the most obvious differences between the wait() and join() method is that former is declared in java.lang.Object class while join() is declared in java.lang.Thread class. This means that wait() is related to the monitor lock which is held by each instance of an object and join method is related to Thread itself. The wait() method is used in conjunction with notify() and notifyAll() method for inter-thread communication, but join() is used in Java multi-threading to wait until one thread finishes its execution.  Another difference between wait() and join() method is that former must be called from synchronized method or block but later can be called without a synchronized block in Java. A good knowledge of differnet thread related methods e.g. start and run, wait and notify, join and yield goes a long way in writing robuts and correct mu...

Explain Difference between synchronized block and method in Java Thread with example

12:47 AM
Synchronized block and synchronized methods are two ways to use synchronized keyword in Java and implement mutual exclusion on critical section of code. Since Java is mainly used to write multi-threading programs,  which present various kinds of thread related issues like thread-safety, deadlock and race conditions, which plagues into code mainly because of poor understanding of synchronization mechanism provided by Java programming language. Java provides inbuilt synchronized and volatile keyword to achieve synchronization in Java. Main difference between synchronized method and synchronized block is selection of lock on which critical section is locked. Synchronized method depending upon whether its a static method or non static locks on either class level lock or object lock. Class level lock is one for each class and represented by class literal e.g. Stirng.class. Object level lock is provided by current object e.g. this instance, You should never mix static and non static sy...

Explain What is Thread and Runnable in Java with Example

12:40 AM
What is Thread in Java ?  Thread in Java is an independent path of execution which is used to run two task in parallel. When two Threads run in parallel that is called multi-threading in Java. Java is multithreaded from the start and excellent support of Thread at language level e.g. java.lang.Thread class, synchronized keyword, volatile and final keyword makes writing concurrent programs easier in Java than any other programming language e.g. C++. Being multi-threaded is also a reason of Java's popularity and being number one programming language. On the other hand if your program divides a task between two threads it also brings lot of programming challenges and issues related to synchronization, deadlock, thread-safety and race conditions. In short answer of question What is Thread in Java can be given like "Thread is a class in Java but also a way to execute something in parallel independently in Java". Thread in Java requires a task which is executed by this thre...

Explain about Difference between Callable and Runnable in Java

12:33 AM
Difference between Callable and Runnable interface in Java is one of the interesting questions from my list of Top 15 Java multi-threading questions, and it’s also very popular in various Java Interviews. The Callable interface is newer than Runnable interface and added on Java 5 release along with other major changes e.g. Generics, Enum, Static imports and variable argument method. Though both Callable and Runnable interface are designed to represent a task, which can be executed by any thread, there is some significant difference between them. In my opinion, the major difference between Callable and Runnable interface is that Callable can return the result of an operation performed inside call() method, which was one of the limitations with Runnable interface. Another significant difference between Runnable and Callable interface is the ability to throw checked exception. The Callable interface can throw checked exception because it's call method throws Exception. Commonly ...

Explain About Volatile in java with example

12:28 AM
What is Volatile variable in Java? volatile variable in Java is a special variable which is used to signal threads, a compiler that this particular variables value are going to be updated by multiple threads inside Java application. By making a variable volatile using the volatile keyword in Java, application programmer ensures that its value should always be read from main memory and thread should not use cached value of that variable from their own stack. With the introduction of Java memory model from Java 5 onwards along with introduction of CountDownLatch, CyclicBarrier, Semaphore and ConcurrentHashMap, volatile variable also guarantees "happens-before" relationship, which means not only another thread has visibility of latest value of volatile variable but also all the variable is seen by the thread which has updated value of volatile variable before these threads sees it. What is volatile variable and when to use it is always a popular Java threading question? ...

How to join threads in Java? Thread.join() example

12:02 AM
You can join two threads in Java by using join() method from java.lang.Thread class. Why do you join threads?  because you want one thread to wait for another before starts processing. It's like a relay race where the second runner waits until the first runner comes and hand over the flag to him. Remember, unlike sleep(), join() is not a static method so you need an object of java.lang.Thread class to call this method. Now, who calls and who wants and which thread dies? for example, if you have two threads in your program main thread and T1 which you have created. Now if your main thread executes this line T1.join() (main thread execute whatever you have written in the main method) then main thread will wait for T1 thread to finish its execution. The immediate effect of this call would be that main thread will stop processing immediately and will not start until T1 thread has finished. So, what will happen if T1 is not yet started and there is no one to start T1 thread? Well,...

.