- Enum Class Thread.State
- Nested Class Summary
- Nested classes/interfaces declared in class java.lang.Enum
- Enum Constant Summary
- Method Summary
- Methods declared in class java.lang.Enum
- Methods declared in class java.lang.Object
- Enum Constant Details
- NEW
- RUNNABLE
- BLOCKED
- WAITING
- TIMED_WAITING
- TERMINATED
- Method Details
- values
- valueOf
- Tech Tutorials
- Friday, December 13, 2019
- Blocking Methods in Java Concurrency
- Examples of blocking methods in Java multi-threading
- Drawback of blocking methods
- Non-Blocking Data Structures
- Non-blocking I/O
- What is blocking methods in Java and how do deal with it? Example
- What are Blocking methods in Java?
- Examples of blocking methods in Java:
- Disadvantages of blocking method
- Best practices while calling a blocking method in Java
- A word of caution:
- Important points:
Enum Class Thread.State
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.
Nested Class Summary
Nested classes/interfaces declared in class java.lang.Enum
Enum Constant Summary
Method Summary
Methods declared in class java.lang.Enum
Methods declared in class java.lang.Object
Enum Constant Details
NEW
RUNNABLE
Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.
BLOCKED
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait .
WAITING
A thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate.
TIMED_WAITING
TERMINATED
Method Details
values
valueOf
Returns the enum constant of this class with the specified name. The string must match exactly an identifier used to declare an enum constant in this class. (Extraneous whitespace characters are not permitted.)
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Tech Tutorials
Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.
Friday, December 13, 2019
Blocking Methods in Java Concurrency
There are methods in Java that execute the task assigned without relinquishing control to other thread. In that case they have to block the current thread until the condition that fulfills their task is satisfied. Since these methods are blocking in nature so known as blocking methods.
A very relevant example of blocking methods in Java, which most of you would have encountered is read() method of the InputStream class. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
Then there is accept() method of the ServerSocket class. This method listens for a connection to be made to this socket and accepts it and blocks until a connection is made.
Since this post is more about blocking methods from the Java multi-threading perspective so let’s have some example from there.
Examples of blocking methods in Java multi-threading
- wait() method— Blocks the current thread until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
- sleep() method— Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
- join() method— Where the current thread is blocked until all the other threads finish.
- BlockingQueue and BlockingDeque interfaces— Starting Java 5 with the introduction of java.util.concurrent package blocking data structures which implements these two interfaces BlockingQueue and BlockingDeque have been added. Some of the examples are ArrayBlockingQueue, LinkedBlockingQueue and LinkedBlockingDeque.
- put(E e)— Inserts the specified element into this queue, which will block if the space is full.
- take()— Retrieves and removes element from the queue, waiting if necessary until an element becomes available.
Drawback of blocking methods
Though it is essential to block threads in order to have some synchronization on the execution order or the access on shared object but at the same time blocking threads may lead to suspension of multiple threads even waiting forever if not handled properly posing a serious threat to scalability and performance.
As example— If a thread holding the lock is waiting for some resource like I/O or delayed due to some other fault then other waiting threads will not make any progress.
Non-Blocking Data Structures
Java 5 has added many data structures in concurrency package that use non-blocking algorithm like atomic variables i.e. AtomicInteger, ConcurrentLinkedQueue or reduce the probability of blocking by using techniques like lock striping as used in ConcurrentHashMap.
Non-blocking I/O
Java NIO’s non-blocking mode in which an I/O operation will never block and may transfer fewer bytes than were requested or possibly no bytes at all from the Channel.
That’s all for this topic Blocking Methods in Java Concurrency. If you have any doubt or any suggestions to make please drop a comment. Thanks!
What is blocking methods in Java and how do deal with it? Example
Blocking methods in Java are those methods that block the executing thread until their operation is finished. A famous example of the blocking method is the InputStream read() method which blocks until all data from InputStream has been read completely. A correct understanding of blocking methods is required if you are serious about Java programming especially in the early days because if not used carefully blocking method can freeze GUIs, hung your program, and become non-responsive for a longer duration of time. In this post, we will see What is Blocking methods in Java, Examples of Blocking methods and Some best practices around blocking methods, and how to use blocking methods in Java.
What are Blocking methods in Java?
As I said Blocking methods are those which block the currently executing thread from further operation until the function returns. So if you have just one thread in your program e.g. main thread and you call any blocking method e.g. reading from InputStream, your program will be blocked until the reading of the file is finished. Javadoc clearly mentions whether an API call is blocking or not but most java IO methods are blocking.
If you have been doing GUI programming in Java using Swing then knowledge of blocking methods becomes even more important for you, because nobody likes freezing or nonresponsive GUI. methods like invokeAndWait are blocking in nature and should be used only when you are performing some operation on which the user should wait for the result.
In most simple terms blocking means, your code in the next line will not be executed because the Thread which is executing the blocking function is waiting for the method to return. here is a code example that helps you to understand blocking calls:
public class 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"); > >
In this code example after executing first print statement your program will be blocked and will not execute second print statement until you enter some chara cters in console and press enter because read() method blocks until some input is available for reading.
Examples of blocking methods in Java:
There are lots of blocking methods in Java API and good thing is that javadoc clearly informs about it and always mention whether a method call is blocking or not. In General methods related to reading or writing file , opening network connection, reading from Socket , updating GUI synchronously uses blocking call. here are some of most common methods in Java which are blocking in nature:
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.
Disadvantages of blocking method
Blocking methods poses significant threat to scalability of System. Imagine you are writing a client server application and you can only serve one client at a time because your code blocks. there is no way you can make use of that System and its not even using resources properly because you might have high speed CPU sitting idle waiting for something.
Yes there are ways to mitigate blocking and using multiple threads for serving multiple clients is a classical solution of blocking call.
Though most important aspect is design because a poorly designed system even if its multi-threaded can not scale beyond a point, if you are relying solely of number of Threads for scalability means it can not be more than few hundred or thousands since there is limit on a number of thread JVM can support.
Java5 addresses this issue by adding non-blocking and asynchron ous alternative of blocking IO calls and those utilities can be used to write high performance
Best practices while calling a blocking method in Java
Blocking methods are for a purpose or may be due to the limitation of API but there are guidelines available in terms of common and best practices to deal with them. here I am listing some standard ways which I employ while using the blocking method in Java
1. If you are writing a GUI application that may be in Swing never call the blocking method in the 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
This will keep your GUI responsive, but again it depends upon design if the operation is something that requires the user to wait then consider using invokeAndWait() for the synchronous update.
2. Always let separate worker thread handles time-consuming operations e.g. reading and writing to file, database or
3. Use timeout while calling the blocking method. so if your blocking call doesn’t return in the specified time period, consider aborting it and returning back but again this depends upon the scenario. if you are using Executor Framework for managing your worker threads, which is, by the way, recommended way then you can use Future object whose get() methods support timeout, but ensure that you properly terminate a blocking call.
4. Extension of first practices, don’t call blocking methods on keyPressed () or paint () method which are supposed to return as quickly as possible.
A word of caution:
Though multi-threading is a workaround of blocking method it poses its own risk like thread-safety and race conditions. Java 5 also provides better alternatives of blocking IO methods wrapped in java.nio package.
That’s all on Blocking methods in Java and some of the best practices to use while calling blocking functions. let’s know what is your experience while using blocking IO methods and what standard code practices you follow while using these methods.
Important points:
1. If a thread is blocked in a blocking method it remains in any of blocking state e.g. WAITING, BLOCKED or TIMED_WAITING.
2. Some of the blocking methods throws checked InterrupptedException which indicates that they may allow cancel the task and return before completion like Thread.sleep() or BlockingQueue.put() or take() throws InterruptedException.
3. interupt() method of Thread class can be used to interuupt a thread blocked inside blocking operation, but this is mere