0

I'm new to dealing with multi-threading. I'm confused in one point and seek clarification. I have the following in the main program:

String hostname = null;
ExecutorService threadExecutor = Executors.newFixedThreadPool(10);
MyThread worker = null;

while(resultSet.next()) { 
  hostname = resultSet.getString("hostName");
  worker = new MyThread(hostname);
  threadExecutor.execute( worker );
}

threadExecutor.shutdown();

while (!threadExecutor.isTerminated()) {
  threadExecutor.awaitTermination(1, TimeUnit.SECONDS);
} 

The class that implements runnable is:

public class MyThread implements Runnable{
  String hostname=null;

  MyThread (String hostname) {
    this.hostname=hostname;
    System.out.println("New thread created");
  }

  public void run() {
    Class1 Obj1 = new Class1();
    try {
      obj1.Myfunction(hostname);
    } catch (Exception e) {
      System.out.println("Got an Exception: "+e.getMessage());
    }
  }
}

I have a variable called hostname. Everythread needs to get this variable as it must be passed to the function Myfunction that every thread needs to execute.

I defined a variable called hostname inside the constructor. Then I sent the variable hostname to MyFunction(hostname). Since hostname is defined inside class MyThread, Then the hostname that it has been sent as an argument to Myfunction is the thread's hostname.

I don't know if there is a need for me to do the assignment this.hostname=hostname?? When do I need to write the word this.? Do I need to send the hostname to Myfunction with the word this.?

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
Jury A
  • 19,192
  • 24
  • 69
  • 93
  • 1
    Hostname should at least be `volatile`. Read about the Java Memory Model and the `happens-before` relationship as an obligatory study before entering the world of concurrent programming in Java. – Marko Topolnik Jul 18 '12 at 11:49
  • Are `MyThread` and `ExtractCertThread` the same thing? – assylias Jul 18 '12 at 11:54
  • 2
    @MarkoTopolnik It only needs to be final. – assylias Jul 18 '12 at 11:55
  • 1
    @assylias True, I didn't pay much attention, just saw him explicitly put that `= null` and assumed there would be a setter. I'll leave the comment because the advice part still holds :) There's a whole lot of nonsense in that code, kind of stifles quick grasping. – Marko Topolnik Jul 18 '12 at 11:59
  • @assylias: yes. Sorry for the typo. This is a toy example for my scenario that's why. – Jury A Jul 18 '12 at 12:14
  • hostname does not need to be volatile if it's being passed in the constructor to the runnable object. It only needs to be volatile if it's being modified by another thread. In this case, you're passing the value in the constructor, and no one is changing it after that. So volatile is not necessary. See here for a typical use case of the keyword: http://www.javamex.com/tutorials/synchronization_volatile_typical_use.shtml – Matt Jul 18 '12 at 12:17
  • @assylias: The word final will ensure that the hostname is fixed for each thread?? But is this essential or just a good practice?? i.e, is the program wrong without the final?? As far as I understand, each worker is an object of MyThread class, and once it is created, it will execute the instructor and will be assigned its own value for the hostname. Could you clarify the purpose of final in this context?? – Jury A Jul 18 '12 at 12:35
  • @JuryA final makes several guarantees, including a visibility guarantee. If you don't make hostname final in MyThread, it is not inconceivable that obj1.MyFunction could see a stale (null) value of hostname. – assylias Jul 18 '12 at 13:10
  • @MarkoTopolnik: When I did use the word final in defining hostname inside MyThread class, I could not assign a value to it since it is constant. – Jury A Jul 25 '12 at 14:02
  • You **did** remove that `= null` when you made it `final`, I hope? – Marko Topolnik Jul 25 '12 at 14:05

2 Answers2

1

You have to use this.hostname in the constructor since you have an argument that is also named hostname, so if you don't use this you are simply storing the argument's value in the argument itself.

In run you don't have to use this since there are no other variables with the same name in the scope of the function.

See also When should I use "this" in a class? and Java - when to use 'this' keyword

Community
  • 1
  • 1
vainolo
  • 6,907
  • 4
  • 24
  • 47
  • Jsut to make sure, if I don't want to use `this`, then, I can change the name of the variable which is in the class `MyThread` to: say, `threadHostname`, and then I can write the assignment in the constructor as: `threadHostname=hostname` without `this` – Jury A Jul 19 '12 at 00:08
1

It looks like your problem is not multi-threading, but the basis concepts of object oriented programming. Let's forget runnable and executors for a moment.

You are defining a class which has an hostname field, and then you define a constructor which takes this parameter and it set the internal value to be that parameter. The keyword this is only necessary in case the parameter to the constructor has the same name of the class field . This is independent from the fact that it is a runnable! You can use it in any other method inside the class like the following.

public class HostNameResolver {

    private String hostname = null;

    public HostNameResolver (String externalValue) {

        this.hostname = externalValue;

    }

    public void addToDb() {
        DbAdder dbAdder = new DbAdder();
        dbAdder.add(hostName);
   }
}

If you want this stuff to be schedulable asynchronously over the Executor abstraction, which is an abstraction over Threads, you need this class to implements the Runnable interface, which contains a method run. The method run is a public method of your class, and has access to all the class private, public and protected properties as any other methods.

The reason is simple: when you submit a Runnable to an ExecutorService, the ExecutorService will pass the Runnable to a Thread as soon as there is one available, and call your run method.

Edmondo
  • 19,559
  • 13
  • 62
  • 115