2

Sorry if this is a common question, can't find an answer.

I wonder if there is a generalisation of the Thread Safe proxies that are available for collections, those that make un-sinchronized collections synchronized.

Using AspectJ, it should be possible to write:

class ThreadSafeProxy
{
  public static <T> T getInstance ( T unsinchronizedObject )
}

which would return an object where all the public methods of unsinchronizedObject would be intercepted and wrapped inside synchronize ( unsinchronizedObject ). Without AspectJ, it should be possible to write:

<T> T static synchronizeMethod ( Object unsynchObject, Class<T> returnType, String methodName, Object... params )

And implement it via reflection. Though this would be slower and probably less practical.

Thanks in advance for any help.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
zakmck
  • 2,715
  • 1
  • 37
  • 53

2 Answers2

2

You could certainly do this, but there might be some problems, such as:

  1. Performance. Your code might become unnecessarily over-synchronized.
  2. Deadlocks. If object A tries to call (directly or indirectly) a method in object B in one thread, while at the same time object B tries to call (directly or indirectly) a method in object A, you would get a deadlock - a type of hang. If this is a possibility, you would have to rethink your approach.
Robin Green
  • 32,079
  • 16
  • 104
  • 187
  • Sure, I'm perfectly aware that by synchronising this simple way one risks these issues more than by working out thread safety more carefully. However, I've just met a case where I only had a couple of methods and these didn't deadlock one each other. I Just needed to write a specific version of the wrapper I've asked about, in order to avoid internal state inconsistencies in the class I was using. This is where I got this question from, I'm not proposing this as a general way to manage thread safety (I'm not so unfamiliar with the topic, nor so nut! :-) ). – zakmck Nov 23 '13 at 19:10
-1

I think java.util.Collections synchronizedCollection method is what you need.

http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29

Jeff Miller
  • 1,424
  • 1
  • 10
  • 19