2

I need to create a class to wrap other classes and methods (3rd party) that are not "thread safe". I actually want to create a single threaded class/method.

This should do it:

public class SomeClass {
    public static synchronized void performTask(int val) {
        //interesting non-thread safe code...
        ThisClass thisclass = new ThisClass();
        thisclass.dostuff();
        ThatClass thatclass = new ThatClass();
        thatclass.dootherstuff();
        HisClass hisclass = new HisClass();
        hisclass.notsure();
    }

1 static class with 1 static method which is synchronized. So if multiple objects are using / calling this class. They will have to wait "in-line". Performance will suffer if heavy load.

public class MyClass {
    public void mytask() {
        //interesting code
        SomeClass.performTask(myval); // will wait if some other code block is in SomeClass.performTask?
    }
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Paul
  • 608
  • 1
  • 9
  • 23
  • 1
    You might have to have a look at this http://stackoverflow.com/questions/437620/java-synchronized-methods-lock-on-object-or-class – SmartCoder Dec 05 '12 at 18:01
  • So if multiple objects are using/calling this class, they will wait "in-line" and performance may suffer if heavy load? – Paul Dec 05 '12 at 19:51
  • If your question is: "will this decrease performance on heavy load?" then the answer is "yes, absolutely" – David ten Hove Nov 04 '14 at 08:28

1 Answers1

0

Synchronization is required in multi-threaded environment. When multiple thread can access your resource concurrently there you may required synchronization on resource access.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103