Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Synchronize the String Type in Java



A thread is a piece of code (under execution) in a program, which executes a sub task of the process independently. independent process.

In other words, a thread is a light weight process which executes a piece of code independently.

Thread synchronization

If a process has multiple threads running independently at the same time (multi-threading) and if all of them trying to access a same resource an issue occurs.

To resolve this, Java provides synchronized blocks/ synchronized methods. If you define a resource (variable/object/array) inside a synchronized block or a synchronized method, if one thread is using/accessing it, other threads are not allowed to access.

synchronized (Lock1) {
   System.out.println("Thread 1: Holding lock 1...");
}

Synchronizing Strings

It is not recommended to use objects which are pooled and reused, if you do so there is a chance of getting into deadlock condition down the line.

Since Strings are pooled in String constant pool and reused, it is not suggestable lock String types with Synchronization.

Updated on: 2020-07-02T10:33:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements