Никто не пробовал multithread JavaAgent в Domino 10?

  • Автор темы Автор темы garrick
  • Дата начала Дата начала

garrick

Lotus Team
26.10.2009
1 357
149
Что-то никак не получается... Магическим образом пропадают Domino объекты (Database, Document, View и пр.) recycle() везде убрал - не помогает.
Задача: обработать за короткое время большое кол-во документов.
 
У меня все таки примера нет полноценного, но есть вот такой класс.
Суть в том, что мы создаем очередь и кидаем туда задачи, которые созданы от NotesTask.

Сам класс взять отсюда.
там же есть набор для обработки коллекции, опять же в потоках

Код на страницах не виден, но он есть, просто движок криво обрабатывает тэги:
1657286886533.png
 

Вложения

У меня все таки примера нет полноценного, но есть вот такой класс.
Суть в том, что мы создаем очередь и кидаем туда задачи, которые созданы от NotesTask.

Сам класс взять отсюда.
там же есть набор для обработки коллекции, опять же в потоках

Код на страницах не виден, но он есть, просто движок криво обрабатывает тэги:
Посмотреть вложение 61147
ну мне не кажется запуск агентов в тредах вещью надёжной :)
там и так всё очень зыбко
 

MONDAY, FEBRUARY 13, 2012​

How to run Domino Java agents in Multi threads​


You could use ExecutorService for Domino Java for running Domino Java agents in the few threads.

There is only one attention:

You know that code will wait until agent.run() or agent.runOnServer() finish. It looks like this methods using thread.wait() for waiting the end of the task. So interrupt() in NotesExecutorService.NotesTask.stopThread() will interrupt not only the NotesTask thread itself but agent.run() also.

If you are using ExecutorService for Domino Java for running agents then you need to run task in the synchronized method to avoid calling .stopThread() [read interrupt()] until it waits agent finishing [read agent.run() done]

Changes under the cut

Form aku.domino.extended.threads.NotesExecutorService.NotesTask.runNotes()

Java:
public void runNotes() {
 while (!isStopped()) {
  try {
   Runnable runnable = (Runnable) taskQueue.dequeue();
   runnable.run();
  } catch (InterruptedException ie){
   //do nothing, this is just stopping
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

To

Java:
public void runNotes() {
 while (!isStopped()) {
  try {
   Runnable runnable = (Runnable) taskQueue.dequeue();
   runTask(runnable);
  } catch (InterruptedException ie){
   //do nothing, this is just stopping
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

private synchronized void runTask(Runnable runnable) {
 runnable.run();
}

Author Andriy Kuba on
 
Последнее редактирование:

FRIDAY, FEBRUARY 10, 2012​

ExecutorService for Domino Java​


ExecutorService is a good to use class, but it have a little problem in domino


It's nice when company politic allow you to fix it like this


If you are not allowed to do it, than you got a little trouble. Fortunately Java is creator friendly language, so you could do ExecutorService himself.

I did NotesExecutorService on the base of next articles:



Modification NotesExecutorService for run multiple thread agents you could find following link

NotesExecutorService itself under the cut

Example of using NotesExecutorService

Java:
NotesExecutorService pool = new NotesExecutorService(10);

WorkThread task  = new WorkThread();
task.setDocument(document);

pool.execute(task);
 
pool.shutdown();

NotesExecutorService

Java:
package aku.domino.extended.example.misc;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import lotus.domino.NotesThread;

/**
 * based on
 * http://java.dzone.com/news/java-concurrency-thread-pools
 * http://tutorials.jenkov.com/java-concurrency/blocking-queues.html
 *
 *  @author aku
 *
 */
public class NotesExecutorService {
 private BlockingQueue queue = null;
 private List<NotesTask> threads = new ArrayList<NotesTask>();
 private boolean isStopped = false;

 public NotesExecutorService(int threadsNumber) {
  queue = new BlockingQueue(threadsNumber);
  startThreads(threadsNumber);
 }

 private void startThreads(int threadsNumber) {
  for (int i = 0; i < threadsNumber; i++) {
   threads.add(new NotesTask(queue));
  }
 
  for (NotesTask thread : threads) thread.start();
 }

 public synchronized void execute(Runnable task) throws Exception {
  if (this.isStopped) throw new IllegalStateException("ThreadPool is stopped");
  this.queue.enqueue(task);
 }

 public synchronized void shutdown() throws InterruptedException {
  this.isStopped = true;
  for (NotesTask thread : threads) {
   thread.stopThread();
   thread.join();
  }
 }

 public class NotesTask extends NotesThread {
  private BlockingQueue taskQueue = null;
  private boolean isStopped = false;

  public NotesTask(BlockingQueue queue) {
   taskQueue = queue;
  }

  @Override
  public void runNotes() {
   while (!isStopped()) {
    try {
     Runnable runnable = (Runnable) taskQueue.dequeue();
     runnable.run();
    } catch (InterruptedException ie){
     //do nothing, this is just stopping
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }

  public synchronized void stopThread() {
   isStopped = true;
   this.interrupt(); // break pool thread out of dequeue() call.
  }

  public synchronized boolean isStopped() {
   return isStopped;
  }
 }

 private class BlockingQueue {

  @SuppressWarnings("rawtypes")
  private List queue = new LinkedList();
  private int limit = 10;

  public BlockingQueue(int limit) {
   this.limit = limit;
  }

  @SuppressWarnings("unchecked")
  public synchronized void enqueue(Object item)throws InterruptedException {
   while (this.queue.size() == this.limit) wait();
   if (this.queue.size() == 0) notifyAll();
   this.queue.add(item);
  }

  public synchronized Object dequeue() throws InterruptedException {
   while (this.queue.size() == 0) wait();
   if (this.queue.size() == this.limit) notifyAll();
   return this.queue.remove(0);
  }

 }

}
 
У меня все таки примера нет полноценного, но есть вот такой класс.
....

У меня так и не взлетело...
Перебираю документы во view, передаю в WorkThread UNID документа, внутри WorkThread заново получаю документ и просто делаю 10 раз System.out.println(document.getUniversalID()). Ломается случайным образом, на любом повторе println. Пропадает документ. Фиксированное количество потоков работает, но с перебором коллекции документов беда.
 
У меня так и не взлетело...
Перебираю документы во view, передаю в WorkThread UNID документа, внутри WorkThread заново получаю документ и просто делаю 10 раз System.out.println(document.getUniversalID()). Ломается случайным образом, на любом повторе println. Пропадает документ. Фиксированное количество потоков работает, но с перебором коллекции документов беда.
доминошные объекты лучше не использовать в таком сценарии, у них с ГЦ всё "странно" ;)
 
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!