3

Can an body explain alternate way to achieve the threadsafe without using the synchronization at method level block level?

public synchronized int disp()
 {

  }



 or
 public int  disp()
 {
  Synchronized
   {}
  }
BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • Read up on http://en.wikipedia.org/wiki/Mutual_exclusion and http://en.wikipedia.org/wiki/Lock_(computer_science). – Anders R. Bystrup Oct 29 '12 at 10:47
  • If there is no state then you don't need `synchronization`. There are various ways. `Volatile`, `ThreadLocal`, delegate to Synchronized collections etc which one to choose depends on the situation. – Amit Deshpande Oct 29 '12 at 10:47
  • It depends a lot on the actual code that you have. – Tudor Oct 29 '12 at 11:06
  • check this http://stackoverflow.com/questions/10330941/thread-safe-code-without-using-the-synchronized-keyword – NPKR Oct 29 '12 at 11:09

2 Answers2

2

You could just use a single thread, of course.

You can design your application to avoid sharing mutable state, so that methods are inherently threadsafe.

You can use synchronized library collections.

You can use threadsafe queues to communicate between threads (Concurrent Queues).

It rather depends on what you are trying to achieve...

DNA
  • 42,007
  • 12
  • 107
  • 146
0

There is another variant called Class Level Synchronization. But it is a kind of Block level synchronization only.

But, before that can you explain in your question why is such requirement?

Azodious
  • 13,752
  • 1
  • 36
  • 71
  • accoding to my view there is no class level synchronization.what is the alternative way to achieve the thread safe of the object – user1782621 Oct 29 '12 at 10:56
  • if you could explain why do you need another way, it will be helpful. is it for learning or are you stuck in some real time problem? – Azodious Oct 29 '12 at 11:06