Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Is there another way to make a java class method a thread safe except using 'synchronized' keyword? If yes what is it ?

user-image
Question added by محمد حسام الدين حسن صدقى , Senior Functional Consultant , Egabi Fsi
Date Posted: 2018/05/21
Rakesh Pati
by Rakesh Pati , Software Engineer , Capgemini

Is is possible using transient

Eranna PK
by Eranna PK , Java Developer , UBQ Technologies pvt ltd

Yes, Using transient keyward

Amrit Kumar
by Amrit Kumar , Java Developer

If we are working servlet then we can can extend with SingleThreadClass. Or for genereal core application don't create any class level variable.

imran Imran
by imran Imran , Principal Software Engineer , Northbay Solutions

ReentrantLock or build you own locking mechanism

Muhammed Bilal Abdulkany
by Muhammed Bilal Abdulkany , IT Systems Analyst , Abu Dhabi Commercial Bank

Well there are many ways you can achieve this, but each contains many flavors. Java 8 also ships with new concurrency features. Some ways you could make sure thread safety are: Semaphores Locks-Reentrantlock,ReadWriteLock,StampedLock(Java 8) 

devagoud rangol
by devagoud rangol , Software Developer , Beta bulls Technologies

by using local variables or java.lang.ThreadLocal

Tasneem K
by Tasneem K , مبرمجة اندرويد , فريلانسر

import java.util.concurrent.atomic.AtomicInteger;   public class MyCounter { private static AtomicInteger counter = new AtomicInteger(0);   public static int getCount() { return counter.getAndIncrement(); } }In this particular counter example, we actually can make count++ atomic by using AtomicInteger from the package "java.util.concurrent.atomic".

Some other useful facts about thread-safe

Local variables are thread safe in Java.

Each thread has its own stack. Two different threads never shares the same stack. All local variables defined in a method will be allocated memory in stack. As soon as method execution is completed by the current thread, stack frame will be removed.

 

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.