我正在开发应用程序,应该从 db 获取用户列表并从目录(ldap 或 AD)更新您的详细信息。我在多核机器上执行此过程,所以我创建了这个应用程序(下面的代码)。我正在使用 CompletionService 并在 Future 对象中获取结果。
一段时间后,我出现“无法创建新的本机线程”消息的内存不足错误。在任务管理器中,我看到该应用程序创建了大量线程,但我要求创建大小等于处理器数量的固定线程池。
我的代码有什么问题?
class CheckGroupMembership {
public static void main(String[] args) throws Exception {
final ExecutorService executor = Executors.newFixedThreadPool(**Runtime.getRuntime().availableProcessors()**);
CompletionService<LdapPerson> completionService =
new ExecutorCompletionService(executor)<LdapPerson>(executor);
final int limit = 2000;
DocumentService service1 = new DocumentService();
List<String> userNamesList = service1.getUsersListFromDB(limit);
List<LdapPerson> ldapPersonList = new ArrayList() <LdapPerson> (userNamesList.size());
LdapPerson person;
for (String userName : userNamesList) {
completionService.submit(new GetUsersDLTask(userName));
}
try {
for (int i = 0, n = userNamesList.size(); i < n; i++) {
Future<LdapPerson> f = completionService.take();
person = f.get();
ldapPersonList.add(person);
}
} catch (InterruptedException e) {
System.out.println("InterruptedException error:" + e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
错误 CheckGroupMembership:85 - java.lang.OutOfMemoryError:无法创建新的本机线程 java.util.concurrent.ExecutionException:java.lang.OutOfMemoryError:无法在 java.util.concurrent.FutureTask$Sync.innerGet 处创建新的本机线程( FutureTask.java:222) 在 java.util.concurrent.FutureTask.get(FutureTask.java:83
GetuserDLs 任务
public class GetUsersDLTask implements Callable<LdapPerson> {
private String userName;
public GetUsersDLTask(String u) {
this.userName = u;
}
@Override
public LdapPerson call() throws Exception {
LdapService service = new LdapService();
return service.getUsersDLs(userName);
}
}