Multithreading interview questions in java for experienced: List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.
Multithreading Interview Questions in Java
Question 1.
What is a thread?
Answer: A thread is a set of instructions executing apart from other threads (with its own stack) but sharing the same memory space (with the same heap).
Question 2.
What is the difference between Process and Thread?
Answer:
The process is a program in execution whereas thread is a separate path of execution in a program.
A process can contain multiple threads. In most multithreading operating systems, a process gets its own memory address space; a thread doesn’t. Threads typically share the heap belonging to their parent process.
For instance, a JVM runs in a single process in the host O/S. Threads in the JVM share the heap belonging to that process; that’s why several threads may access the same object.
Typically, even though they share a common heap, threads have their own stack space. This is how one thread’s invocation of a method is kept separate from another’s. This is all a gross oversimplification, but it’s accurate enough at a high level. Lots of details differ between operating systems.
Java runtime environment runs as a single process that contains different classes and programs as processes. Thread can be called a lightweight process. Thread requires fewer resources to create and exists in the process, thread shares the process resources.
Table
Question 3.
What are the benefits of multi-threaded programming?
Answer:
In Multi-Threaded programming, multiple threads are executing concurrently which improves the performance because the CPU is not idle in case some thread is waiting to get some resources. Multiple threads share the heap memory, so it’s good to create multiple threads to execute some task rather than creating multiple processes. For example, Servlets are better in performance than CGI because Servlets support multi-threading but CGI doesn’t.
Question 4.
Difference between multithreading and multitasking?
Answer:
A Web Server understands and supports only HTTP protocol whereas an Application Server supports HTTP, TCP/IP, and many more protocols. Also, many more features such as Caches, Clusters, Load Balancing are there in Application Servers which are not available in Web Servers. We can also Configure Application Servers to work as Web Server. In short, Application Server is a superset of which the Web Server is a subset.
Question 5.
How does multithreading take place on a computer with a single CPU?
Answer:
The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
Question 6.
What is the difference between a lightweight and a heavyweight process?
Answer:
[Short answer: threads are lightweight, programs (aka processes or tasks) are heavyweight.] Lightweight and heavyweight processes refer to the mechanics of a multi-processing system.
In a lightweight process, threads are used to divvy up the workload. Here you would see one process executing in the OS (for this application or service.) This process would possess 1 or more threads. Each of the threads in this process shares the same address space. Because threads share their address space, communication between the threads is simple and efficient. Each thread could be compared to a process in a heavyweight scenario.
In a heavyweight process, new processes are created to perform the work in parallel. Here (for the same application or service), you would see multiple processes running.
Each heavyweight process contains its own address space. Communication between these processes would involve additional communications mechanisms such as sockets or pipes.
The benefits of a lightweight process come from the conservation of resources. Since threads use the same code section, data section, and OS resources, fewer overall resources are used. The drawback is now you have to ensure your system is thread-safe. You have to make sure the threads don’t step on each other. Fortunately, Java provides the necessary tools to allow you to do this.
Question 7.
What is the difference between user Thread and daemon Thread?
Answer:
When we create a Thread in a java program, it’s known as a user thread. A daemon thread runs in the background and doesn’t prevent JVM from terminating. When there are no user threads running, JVM shutdown the program and quits. A child thread created from a daemon thread is also a daemon thread.
Question 8.
How can we create a Thread in Java?
Answer:
There are two ways to create Thread in Java – first by implementing Runnable interface and then creating a Thread object from it and second is to extend the Thread class. Read this post to learn more about creating threads in java.
Question 9.
What are the different stages in the lifecycle of Thread?
Answer:
When we create a Thread in a java program, its state is New. Then we start the thread that changes its state to Runnable. Thread Scheduler is responsible to allocate CPU to threads in the Runnable thread pool and change their state to Running. Other Thread states are Waiting, Blocked, and Dead. Read this post to learn more about the life cycle of the thread.
Question 10.
What is the atomic operation? What are atomic classes in Java Concurrency API?
Answer:
Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessary for a multi-threaded environment to avoid data inconsistency.
int++ is not an atomic operation. So by the time one thread reads its value and increment it by one, another thread has read the older value leading to the wrong result. To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent. atomic provides wrapper classes for int and long that can be used to achieve this atomically without the usage of Synchronization. Go to this article to learn more about atomic concurrent classes.
Question 11.
What is the Lock interface in Java Concurrency API? What are its benefits over synchronization?
Answer:
The lock interface provides more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties and may support multiple associated Condition objects.
The advantages of a lock are
- It’s possible to make them fair
- It’s possible to make a thread responsive to interruption while waiting on a Lock object.
- It’s possible to try to acquire the lock, but return immediately or after a timeout, if the lock can’t be acquired
- It’s possible to acquire and release locks in different scopes, and in different orders
Question 12.
What is Executors Framework?
Answer:
In Java 5, the Executor framework was introduced with the java.util.concurrent. Executor interface. The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies. Creating a lot many threads with no bounds to the maximum threshold can cause the application to run out of heap memory. So, creating a ThreadPool is a better solution as a finite number of threads can be pooled and reused. Executors framework facilitate the process of creating Thread pools in java. Check out this post to learn with example code to create thread pool using Executors framework.
Question 13.
What is BlockingQueue? How can we implement the Producer-Consumer problem using Blocking Queue?
Answer:
java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element. BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control. BlockingQueue interface is part of the java collections framework and it’s primarily used for implementing producer-consumer problems.
Question 14.
What is Callable and Future?
Answer:
Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.
The callable interface uses Generic to define the return type of Object. Executors class provides useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util. concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get( ) method that can wait for the Callable to finish and then return the result.
Question 15.
What is FutureTask Class?
Answer:
Futuremark is the base implementation class of the Future interface and we can use it with Executors for asynchronous processing. Most of the time we don’t need to use FutureTask class but it comes really handy if we want to override some of the methods of the Future interface and want to keep most of the base implementation. We can just extend this class and override the methods according to fb our requirements. Check out the Java FutureTask Example post to learn how to use it and what are different methods it has.
Question 16.
What are Concurrent Collection Classes?
Answer:
Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next( ) will throw ConcurrentModificationException.
Concurrent Collection classes support full concurrency of retrievals and adjustable expected concurrency for updates.
Major classes are ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet, check this post to learn how to avoid ConcurrentModificationException when using iterator.
Question 17.
what is Executors Class?
Answer:
Executors class provide utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes. Executors class can be used to easily create Thread Pool in java, also this is the only class supporting the execution of Callable implementations.
Question 18.
W^hat are some of the improvements in Concurrency API in Java 8?
Answer:
Some important concurrent API enhancements are:
- ConcurrentHashMap compute( ), forEach( ), forEachEntry( ), forEachKey( ), forEachValue( ), merge( ), reduce( ) and search( ) methods.
- CompletableFuture that may be explicitly completed (setting its value and status).
- Executors newWorkStealingPoolO method to create a work-stealing thread pool using all available processors as its target parallelism level.
Question 19.
Explain Java Thread Life cycle.
Answer:
The life cycle of threads in Java is very similar to the life cycle of processes
running in an operating system. During its life cycle, the thread moves from one
state to another depending on the operation performed by it or performed on it. A
Java thread can be in one of the following states:
• NEW: A thread that is just instantiated is in the new state. When a start 0 method is invoked, the thread moves to the ready state from which it is automatically moved to a runnable state by the thread scheduler.
• RUNNABLE (ready_running) A thread executing in the JVM is in a running state.
• BLOCKED A thread that is blocked waiting for a monitor lock is in this state. This can also occur when a thread performs an I/O operation and moves to the next (runnable) state.
• WAITING for A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
• TIMED_WAITING (sleeping) A thread that is waiting for another thread to perform an action up to a specified waiting time is in this state.
• TERMINATED (dead) A thread that has exited is in this state.
Question 20.
What are the states associated with the thread?
Answer:
The thread contains ready, running, waiting, and dead states.
Question 21.
What state is a thread in when it is executing?
Answer:
An executing thread is in the running state.
Question 22.
How can a dead thread be restarted?
Answer:
A dead thread cannot be restarted.
Question 23.
What are the different ways of creating a thread?
Answer:
There are two ways of creating a thread.
• Implementing Runnable: The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example
public class HelloRunnable implements Runnable { public void run( ) { system. out.println(“Hello from a thread!”); } public static void main(string args[]) { (new Thread(new HelloRunnable( ))).start(); } }
• Subclass Thread: The Thread class itself implements Runnable interface, though it runs method does nothing. An application can subclass Thread, and provides its own implementation of the run, as in the HelloThread example:
public class HelloThread extends Thread { public void run( ) { System. out.println(“Hello from a thread!”); } public static void main(string args[ ]) { (new HelloThread( )).start( ); } }
Question 24.
What are the differences between extending the Thread class and implementing the Runnable interface?
Answer:
Extending the Thread class will make your class unable to extend other classes, because of the single inheritance feature in JAVA. However, this will give you a simpler code, structure. If you implement runnable, you can gain better object-oriented design and consistency and also avoid the single inheritance problems.
Question 25.
When is a thread created?
Answer:
A thread is created by the VM behind the scenes during a call to the start( ) method. It begins its life inside the run( ) method of the thread subclass instance whose start( ) method was called.
Question 26.
Hem do I create a new thread and have it start running?
Answer:
Creating a thread involves creating a new Thread and invoking its start( ) method. Calling start( ) causes the run( ) method of the Thread subclass or the Runnable object passed to the Thread constructor to execute.
Thread t1 = new Thread( ) { public void run( ) { for (int i=0; i<100; i++) { System.out.println(“Tastes Great”); } } }; Runnable r = new Runnable( ) { public void run( ) { for (int i=0; i<100; i++) { system.out.println(“Less Filling”); } } }; Thread t2 = new Thread(r); t1.start( ); t2.start( );
Question 27.
What is the use of the start( ) function in starting a thread? Why we don’t use the run( ) functions directly to run the thread?
Answer:
The start( ) method tells the Java Virtual Machine that it needs to create a system-specific thread. After creating the system resource, it passes the Runnable object to it to execute its run( ) method. Calling the run( ) method directly has the “Thread” execute in the same thread as the calling object, not in a separate thread of execution, as intended.
In other words, calling run( ) is just like a normal method call. Whereas, calling start( ) tells the thread to create the necessary system resources and then execute the run( ) method asynchronously.
Question 28.
Can each Java object keep track of all the threads that want to exclusively access it?
Answer:
Yes.
- Invoking its sleep ( ) methods,
- By blocking on I/O
- By unsuccessfully attempting to acquire an object’s lock
- By invoking an object’s wait( ) method.
- It can also enter the waiting state by invoking its (deprecated) suspend( ) method.
Thread t1 = new Thread(runnable); t1.start( ); // do stuff . . . // wait for tl to finish t1. join( )
try { Thread.sleep(3000); // 3 seconds } catch (interruptedException e) { System.err.prinlnt(“You interrupted me”); }
Thread t = new MyThread( ); t.start( ); try { t.sleep(3000); } catch (interruptedException e) { System.err.prinlnt(“You interrupted me”); }
It will pause the current thread, meaning the thread executing the shown code, not the child thread (t/MyThread).
thread2.start( ); // do more stuff here thread2.join( ); System.out.print!n(“Done”);
public class LocalThreadvars implements Runnable { static private class MyThreadLocal extends ThreadLocal { protected object initialvalue( ) { return new Double (Math.random( ) * 1000.0); } } static ThreadLocal threadLocal = new MyThreadLocal( ); static int counter = 0; private LocalThreadvars( ) { counter++; } public void run( ) { LocalThreadvars myLTV = new LocalThreadvars( ); displayvalues( ); try { Thread.currentThread( ).sleep (((Double) threadLocal .get( )) .longvalue( )); myLTV. displayvalues( ); } catch (interruptedException e) { e.printStackTrace( ); } } private void displayvalues( ) { System.out.println (threadLocal.get( ) + “\t” + counter + “\t” + Thread. currentThread( ) .getName( )); } public static void main (String args[ ]) { LocalThreadvars 1 tv = new LocalThreadvars( ); 1 tv. displayvalues( ); for (int i=0;i<5;i++) { Thread t = new Thread (Itv); t.start( ); } } }
Question 52.
Is there a separate stack for each thread in Java?
Answer:
No
Every thread of execution on any given platform has its own context, which contains an execution state, and a set of access rights (among other things). A thread’s access rights are equal to that of the parent thread, minus rights denied by the parent. In Java, all threads of execution, and thread groups within an applet (or application) belong to a parent ThreadGroup object. A thread’s access to Java resources is therefore determined by its parent ThreadGroup object (including the thread of execution that passes through init( ), start( ), stop( ), processEvent(…),
synchronized (foo) { ... } Acquires a lock on the object instance “foo” at the open brace, and releases the lock at the close brace. synchronized (this) { ... } Acquires a lock on the current object instance (“this”) at the open brace, and releases the lock at the close brace. synchronized void bar( ) { ... } } Acquires a lock on the current object instance at the open brace, and releases it at the close brace. This is equivalent (*) to void bar( ) { synchronized (this) { ... } } class Foo { synchronized static void bar( ) { ... } }
Acquires and releases a lock on the class instance of class Foo. Every class, when loaded, is given an instance of class Class. That means that no matter who invokes method Foo. bar( ), the lock will be on the static instance, and not on any specific instance of class Foo.
- Only one thread can execute a synchronized static method per class.
- Only one thread per instance of the class can execute a non-static synchronized method.
- Any number of threads can execute a non-synchronized method static or non-static method.
synchronized (foo) { ... } Acquires a lock on the object instance “foo” at the open brace, and releases the lock at the close brace. synchronized (this) { ... } Acquires a lock on the current object instance (“this”) at the open brace, and releases the lock at the close brace, synchronized void bar( ) { ... } Acquires a lock on the current object instance at the open brace, and releases it at the close brace. This is equivalent (*) to void bar( ) { synchronized (this) { ... } } class Foo { synchronized static void bar) { ... } }
Acquires and releases a lock on the class instance of class Foo. Every class, when loaded, is given an instance of class Class. That means that no matter who invokes method Foo. bar( ), the lock will be on the static instance, and not on any specific instance of class Foo.
JVM invokes the thread’s run( ) method when the thread is initially executed.
Question 79.
What is the difference between yielding and sleeping?
Answer:
When a task invokes its yield( ) method, it returns to the ready state. When a task invokes its sleep( ) method, it returns to the waiting state.
Question 80.
What’s the difference between the methods sleep( ) and wait()?
Answer:
The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000), causes a wait of up to two 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.
Question 81.
What is a transient variable?
Answer:
A transient variable is a variable that may not be serialized during Serialization and which is initialized by its default value during de-serialization.
Question 82.
What is the daemon thread?
Answer:
Daemon thread is a low priority thread, which runs intermittently in the background doing the garbage collection operation for the java runtime system.
Question 83.
Is there any limitation on the number of daemon threads in an application?
Answer:
No, there is no limitation on the number of daemon threads in an application.
Question 84.
How can a daemon thread be implemented?
Answer:
After creating an object of a Thread class and before starting the thread, call the setDeamon ( ) functions of the Thread class with parameter as true. This will mark the thread as a daemon thread.
Question 85.
When should I use setDaemon( ) and why?
Answer:
Use setDaemon( ) to tell the JVM to make the thread a daemon thread. According to Webster’s, a daemon (variant of demon) is an attendant power or spirit. Daemon threads are typically used to perform services for your application/applet (such as loading the “fiddley bits”). The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated or starved to death (See the “Starvation” FAQ, #41875). Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution. Use daemons as the minions they are.
[In short: daemon threads do not keep the program from quitting; user threads do.]
Question 86.
Which method is used to create the daemon thread?
Answer:
setDaemon method is used to create a daemon thread.
Question 87.
Which method must be implemented by all threads?
Answer:
All tasks must implement the run( ) method
Question 88.
What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?
Answer:
Multithreading is the mechanism in which more than one thread runs independently of each other within the process.
wait ( )* notify ( ) and notifyAll( ) methods can be used for inter-thread communication and these methods are in the Object class.
wait( ): When a thread executes a call to wait( ) method, it surrenders the object lock and enters into a waiting state.
notify( ) or notifyAll( ) : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
Question 89.
Why are the methpds wait() and notify() defined in the Object class when they are used with Threads?
Answer:
The wait( ) and notify( ) methods are object.-specific. The waitO^method suspends the current thread of execution, and tells the object to keep track of the suspended thread. The notify( ) method tells the object to wake up the suspended threads that it is currently keeping track of. Since wait( ) and notify( ) object
specific, they must be used within code that is synchronized on the object in question.
It is also important to use state variables when using wait( ) and notify( ), as threads can be woken up by conditions other than notify( ).
Question 90.
What is the purpose of the wait( ), notify( ), and notifyAll( ) methods?
Answer:
The wait( ), notify( ), and notifyAll( ) methodf are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object’s wait( ) method, it enters the waiting state. It only enters the ready state after another thread invokes the object’s notify( ) or notifyAll( ) methods.
Question 91.
What is “starvation” when used in the context of the Java threading model? ‘
Answer:
Starvation is when the Java runtime (JVM) doesn’t allocate time to a thread to execute. This may be due to a poor scheduling algorithm (like green Threads under Solaris, where a for loop from 1 to 1 million doing something CPU intensive wouldn’t yield the CPU under Solaris but would under Windows), poor programming practice (not returning from the paintO method in an applet), or a hostile attack (like hitting a host with a denial of service attack where the CPU is busy outside the Java process).
Question 92.
What happens when a thread cannot acquire a lock on an object?
Answer:
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.
Question 93.
What is the meaning of calling a method or object “thread-safe?”
Answer:
Basically, calling a method “thread-safe” means that even if multiple threads try to access it simultaneously, nothing bad happens. Here “bad” usually means that due to race conditions, or deadlock, or other pitfalls, the object’s state gets corrupted, or its methods produce unreliable results. A method usually achieves thread-safety by protecting access to shared resources. This usually translates to using the Java synchronized keyword to protect blocks of code that access instance variables, or other shared variables.
For an object to be thread-safe, it must be possible for multiple threads to simultaneously access the same method, or multiple methods, in that object. Usually this is achieved by assuring that each method is thread-safe, but this doesn’t always suffice, since methods can call each other in strange ways, leading to deadlock and other weirdness.
It is very difficult to prove that an object is thread-safe. The main rule of thumb for making thread-safe objects is, “Make all the instance variables private, and all the public accessor methods synchronized.” However, this is sometimes difficult to achieve in practice, due to exigencies of performance, architecture, or implementation. Accurate multithreaded programming is a true art, and very difficult to master. Read “Java Threads” by Oaks and Wong, and “Concurrent Programming in Java” by Lea, for inspiration in your quest to become a thread-safe programmer.
Question 94.
What is the keyword volatile used for? What sort of situations should I use volatile when developing a multi-threaded application?
Answer:
Volatile modifiers tells the compiler that the variable can be changed unexpectedly by another part of programme. When you have nore than one thread and you expect any thread can change the variable you should use volatile. This will tell the compiler to check for the master copy of this variable. Mostly used for boolean flags.
Question 95.
When and why IllegalMonitorStateException throw?
Answer:
Thrown to indicate that a thread has attempted to wait on an object’s monitor or to notify other threads waiting on an object’s monitor without owning the specified monitor.
According to the JavaDoc, IllegalMonitorStateException is thrown “to indicate that a thread has attempted to wait on an object’s monitor or to notify other threads waiting on an object’s monitor without owning the specified monitor.”
As explained in How do wait and notify really work? in order to call foo.wait( ) or foo. notify( ), the calling thread must own a lock on object foo. This exception is thrown if you call it without a preceding synchronized (foo).
Question 96.
What is the relationship between synchronized and volatile keywords?
Answer:
The JVM is guaranteed to treat reads and writes of data of 32 bits or less as atomic. (Some JVM might treat reads and writes of data of 64 bits or less as atomic in future) For long or double variable, programmers should take care in multi-threading environment. Either put these variables in a synchronized method or block, or declare them volatile.
Question 97.
What factors are used to decide using synchronized or volatile?
Answer:
Whether you use volatile or synchronized depends on several factors.
a) If you are not updating many variables often in a multithread environment, consider using volatile.
b) If you are updating many variables, consider using synchronized, because using volatile might be slower.
Question 98.
Two methods have keywords static synchronized and synchronized separately. What is the difference between them?
Answer:
Both are synchronized methods. One is instance method, the other is the class method. The method with static modifier is a class method. That means the method belongs to class itself and can be accessed directly with class name and is also called Singleton design. The method without a static modifier is an instance method. That means the instance method belongs to its object. Every instance of the class gets its own copy of its instance method.
Since both methods are synchronized methods, you are not asked to explain what is a synchronized method. You are asked to tell the difference between instance and class method. Of course, your explanation of how synchronized keyword works doesn’t hurt. And you may use this opportunity to show your knowledge scope. When synchronized is used with a static method, a lock for the entire class is obtained. When synchronized is used with a non-static method, a lock for the particular object (that means instance) of the class is obtained.
Question 99.
What is mutual exclusion? How can you take care of mutual exclusion using Java threads?
Answer:
Mutual exclusion is a phenomenon where no two processes can access critical regions of memory at the same time. Using Java multithreading we can arrive at mutual exclusion. For mutual exclusion, you can simply use the synchronized keyword and explicitly or implicitly provide an Object, any Object, to synchronize on. The synchronized keyword can be applied to a class, to a method, or to a block of code. There are several methods in Java used for communicating mutually exclusive threads such as wait(), notify( ), or notifyAll( ). For example, the notifyAll( ) method wakes up all threads that are in the wait list of an object.
Question 100.
Can Java objects be locked down for exclusive use by a given thread?
Or
what happens when a thread cannot acquire a lock on an object?
Answer:
Yes. You can lock an object by putting it in a “synchronized” block. The locked object is inaccessible to any thread other than the one that explicitly claimed sjt. If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.
Question 101.
What do you understand by Synchronization?
Or
What is synchronization and why is it important?
Or
Describe synchronization in respect to multithreading?
Or
What is synchronization?
Answer: With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.
E.g. synchronizing a function: public synchronized void Methodl ( ) { // method code. } E.g. synchronizing a block of code inside a function: public Method2 ( ){ synchronized (this) { // synchronized code here. } }
Question 102.
When you will synchronize a piece of your code?
Answer:
When you expect that your shared code will be accessed by different threads and these threads may change a particular data causing data corruption, then they are placed in a synchronized construct or a synchronized method.